PHP: 如何将GZ解压成字符串?
PHP: How to uncompress GZ to a string?
我需要从远程服务器检索 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}");
不要忘记在您的 development/production 服务器上安装并启用 Zlib。
您可以使用 gzuncompress()
解压缩字符串,但使用 gzuncompress 有一些缺点,例如字符串长度限制和校验和的一些问题。
您可以使用此 shorthand 代码实现预期的结果,但我建议根据数据(您接收的)的压缩方式检查额外的资源。
<?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?
或者简单地说:
$sitemap = 'http://example.com/sitemaps/sitemap.xml.gz';
$xml = new SimpleXMLElement("compress.zlib://$sitemap", NULL, TRUE);
我需要从远程服务器检索 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}");
不要忘记在您的 development/production 服务器上安装并启用 Zlib。
您可以使用 gzuncompress()
解压缩字符串,但使用 gzuncompress 有一些缺点,例如字符串长度限制和校验和的一些问题。
您可以使用此 shorthand 代码实现预期的结果,但我建议根据数据(您接收的)的压缩方式检查额外的资源。
<?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?
或者简单地说:
$sitemap = 'http://example.com/sitemaps/sitemap.xml.gz';
$xml = new SimpleXMLElement("compress.zlib://$sitemap", NULL, TRUE);