1

I need to retrieve a GZ compressed XML file from a remote server and parse it via simplexml_load_string. Is there a way to do this without uncompressing the GZ to a file, then reading that file via simplexml_load_file? I want to skip what seems like an unnecessary step to me.

Community
  • 1
  • 1
StackOverflowNewbie
  • 39,403
  • 111
  • 277
  • 441

3 Answers3

5

You should be able to do it with the gzdecode function from the Zlib library.

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

More about gzdecode() from the PHP Docs.

However, there is even an easier way, and it's by using a compression wrapper.

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

Or even better:

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

Don't forget to install and enable Zlib on your development/production server.

Inigo Flores
  • 4,461
  • 1
  • 15
  • 36
0

You can uncompress the string using gzuncompress() but there are some drawbacks using gzuncompress like limitation of the string length and some issues with the checksum.

You can achieve the result you expected with this shorthand code but I suggest to check extra resources depending on how the data (you are receiving) is compressed.

<?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?

Community
  • 1
  • 1
Ugur
  • 1,679
  • 14
  • 20
0

Or simply :

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