【问题标题】:Load gzipped XML file with simplexml_load_file()使用 simplexml_load_file() 加载 gzip 后的 XML 文件
【发布时间】:2011-08-07 15:19:01
【问题描述】:

我正在尝试使用 simplexml_load_file() PHP 函数加载一个 gzip 压缩的 XML 文件,但我不知道如何对其进行解码,以便可以使用其中的数据。

【问题讨论】:

  • @Marek Sebera - 此函数 (gzdecode) 在手册中,但在 PHP 中不存在。
  • @Pawel:当然它是 PHP 的一部分,你只需要启用扩展,参见 php.net/manual/en/zlib.installation.php - 这是一个非常常见的扩展。
  • 我启用了这个扩展,但我不能使用这个功能(我安装了 PHP 5.3.6)。我可以使用例如 gzuncompress() 所以我启用了这个扩展。

标签: php gzip simplexml decode


【解决方案1】:

PHP 有support for zlib compression 内置,只需在文件路径前加上compress.zlib:// 的gzip 数据,就完成了:

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

像魅力一样工作。

【解决方案2】:
/*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;
}

【讨论】:

    【解决方案3】:

    使用file_get_contents() 将其读入字符串 使用gzuncompress()解压 并使用 simplexml_load_string() 将字符串作为 XML 加载。

    【讨论】:

    • Readgzfile() 直接发送到浏览器,它不返回字符串。
    • 嗯,为什么不直接simplexml_load_file("compress.zlib://test.xml");instead
    • 我不知道。如果它有效,这是一个很好的解决方案。我赞成你的回答。 :)
    • @Pawel: Checkout Streams in PHP,它们是语言的强大工具,值得了解。这个概念也存在于其他语言中,所以了解一下会更好;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多