PHP:如何将GZ解压缩为字符串?

时间:2015-12-09 20:08:09

标签: php xml gz

我需要从远程服务器检索GZ压缩的XML文件,并通过simplexml_load_string解析它。有没有办法在没有uncompressing the GZ to a file的情况下执行此操作,然后通过simplexml_load_file读取该文件?我想跳过对我来说似乎不必要的一步。

3 个答案:

答案 0 :(得分:2)

你应该可以使用Zlib库中的gzdecode函数来完成它。

$uncompressedXML = gzdecode(file_get_contents($url));

有关gzdecode() from the PHP Docs的更多信息。

然而,甚至有一种更简单的方法,而且使用compression wrapper

$uncompressedXML= file_get_contents("compress.zlib://{$url}");

甚至更好:

$xmlObject=simplexml_load_file("compress.zlib://{$url}");

不要忘记在开发/生产服务器上安装和启用Zlib。

答案 1 :(得分:0)

您可以使用gzuncompress()解压缩字符串,但使用gzuncompress存在一些缺点,例如字符串长度的限制以及校验和的一些问题。

您可以使用此速记代码获得预期的结果,但我建议根据数据(您接收的)的压缩方式检查额外的资源。

<?php
$compressed   = gzcompress('<?xml version="1.0" encoding="UTF-8"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Dont forget me this weekend!</body></note>', 9);
$uncompressed = gzuncompress($compressed);
$xml = simplexml_load_string($uncompressed);
var_dump($xml);

http://php.net/manual/en/function.gzcompress.php

http://php.net/manual/en/function.gzdecode.php

http://php.net/manual/tr/function.gzuncompress.php

Why PHP's gzuncompress() function can go wrong?

答案 2 :(得分:0)

或者简单地说:

$sitemap  = 'http://example.com/sitemaps/sitemap.xml.gz';
$xml = new SimpleXMLElement("compress.zlib://$sitemap", NULL, TRUE);