9

I am struggling to read gzipped xml files in php.

I did succeed in reading normal xml files, using XMLReader() like this:

$xml = new XMLReader();
$xml->open($linkToXmlFile);

However, this does not work when the xml file is gzipped. How can I unzip the file and read it with the XMLReader?

hakre
  • 193,403
  • 52
  • 435
  • 836
Fortega
  • 19,463
  • 14
  • 75
  • 113

3 Answers3

24

As you didn't specify a PHP version, I am going to assume you are using PHP5.

I am wondering why people haven't suggested using the built in PHP compression streams API.

$linkToXmlFile = "compress.zlib:///path/to/xml/file.gz";
$xml = new XMLReader();
$xml->open($linkToXmlFile);

From what I understand, under the covers, it will transparently decompress the file for you and allow you to read it as if were a plain xml file. Now, that may be a gross understatement.

Jordan S. Jones
  • 13,703
  • 5
  • 44
  • 49
4

Maybe the function gzdecode could help you : the manual says (quote) :

Decodes a gzip compressed string

So, you'd have to :

  • download the XML data
  • get it as a string
  • decompress it with gzdecode
  • work on it with XMLReader

That would depend on the right extension (zlib I guess) beeing installed on your server, though...

Mark: Expanding on Pascal's post, here is some example code that should work for you

$xmlfile = fopen($linkToXmlFile,'rb');
$compressedXml = fread($xmlfile, filesize($linkToXmlFile));
fclose($xmlfile);
$uncompressedXml = gzdecode($compressedXml); 

$xml = new XMLReader();
$xml->xml($uncompressedXml);
Community
  • 1
  • 1
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • I had just tried this very thing before I arrived here. This does not work because, for some reason, gzdecode (and gzread) strip all the XML tags and return only the values. – Adam Winter Jul 19 '21 at 18:31
2

Expanding on Pascal's post, here is some example code that should work for you

$xmlfile = fopen($linkToXmlFile,'rb');
$compressedXml = fread($xmlfile, filesize($linkToXmlFile));
fclose($xmlfile);
$uncompressedXml = gzdecode($compressedXml); 

$xml = new XMLReader();
$xml->xml($uncompressedXml);
Mark
  • 6,254
  • 1
  • 32
  • 31
  • If it was all about adding a code-example, why don't you just edit the depending post and add it? – hakre Oct 22 '13 at 12:39