【发布时间】:2015-12-09 20:08:08
【问题描述】:
我需要从远程服务器检索 GZ 压缩 XML 文件并通过 simplexml_load_string 解析它。有没有办法在没有uncompressing the GZ to a file 的情况下做到这一点,然后通过simplexml_load_file 读取该文件?我想跳过对我来说似乎不必要的步骤。
【问题讨论】:
我需要从远程服务器检索 GZ 压缩 XML 文件并通过 simplexml_load_string 解析它。有没有办法在没有uncompressing the GZ to a file 的情况下做到这一点,然后通过simplexml_load_file 读取该文件?我想跳过对我来说似乎不必要的步骤。
【问题讨论】:
您应该可以使用 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。
【讨论】:
您可以使用 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
【讨论】:
或者简单地说:
$sitemap = 'http://example.com/sitemaps/sitemap.xml.gz';
$xml = new SimpleXMLElement("compress.zlib://$sitemap", NULL, TRUE);
【讨论】: