4

I'm trying to load a gzipped XML file using simplexml_load_file() PHP function, but I don't know how to decode it so I can use the data in it.

hakre
  • 193,403
  • 52
  • 435
  • 836
SnackerSWE
  • 649
  • 1
  • 10
  • 19
  • http://www.php.net/manual/en/function.gzdecode.php or – Marek Sebera Aug 07 '11 at 15:21
  • @Marek Sebera - This function (gzdecode) is in the manual but doesn't exist in PHP. –  Aug 07 '11 at 15:59
  • @Pawel: Sure it's part of PHP, you only need to have the extension enabled, see http://www.php.net/manual/en/zlib.installation.php - it's a very common extension. – hakre Aug 07 '11 at 16:14
  • 1
    I have this extension enabled and I can't use this function (I have PHP 5.3.6 installed). I can use e.g gzuncompress() so I have this extension enabled. –  Aug 07 '11 at 16:31

3 Answers3

11

PHP has support for zlib compression build-in, just prefix the path of your file with the gzip'ed data with compress.zlib:// and you're done:

$xml = simplexml_load_file("compress.zlib://test.xml");

Works like a charm.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • X-Ref: [More links to related questions and PHP bugreports](http://stackoverflow.com/a/14978162/367456) – hakre Feb 20 '13 at 11:32
4
/*EDIT  print_r(gzdecoder(simplexml_load_file('test.xml')));
 (Not sure without testing that the internals of what loads the xml 
  in *_load_file would see the gzipped content as invalid)
*/

   $xml=simplexml_load_string(gzdecoder(file_get_contents('test.xml')));
   print_r( $xml);

function gzdecoder($d){
    $f=ord(substr($d,3,1));
    $h=10;$e=0;
    if($f&4){
        $e=unpack('v',substr($d,10,2));
        $e=$e[1];$h+=2+$e;
    }
    if($f&8){
        $h=strpos($d,chr(0),$h)+1;
    }
    if($f&16){
        $h=strpos($d,chr(0),$h)+1;
    }
    if($f&2){
        $h+=2;
    }
    $u = gzinflate(substr($d,$h));
    if($u===FALSE){
        $u=$d;
    }
    return $u;
}
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
3

Read it to a string using file_get_contents() decompress it using gzuncompress() and load string as XML using simplexml_load_string().

hakre
  • 193,403
  • 52
  • 435
  • 836
  • Readgzfile() sends it directly to the browser, it doesn't return a string. – SnackerSWE Aug 07 '11 at 15:31
  • 3
    Hmm, why not just `simplexml_load_file("compress.zlib://test.xml");` [instead](http://stackoverflow.com/questions/6973672/load-gzipped-xml-file-with-simplexml-load-file/6973867#6973867)? – hakre Aug 07 '11 at 16:12
  • @Pawel: Checkout [Streams in PHP](http://www.php.net/manual/en/intro.stream.php), they are a powerful tool of the language, worth to know about. The concept exists in other languages, too, so it's just even better to know about ;) – hakre Aug 07 '11 at 19:16