Load gzipped XML file with simplexml_load_file(

2019-01-19 22:56发布

问题:

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.

回答1:

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



回答2:

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.



回答3:

/*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;
}