我正在通过curl检索一个gzip压缩网页,但是当我将检索到的内容输出到浏览器时,我只得到原始的gzip压缩数据。如何在PHP中解码数据?

我找到的一种方法是将内容写入tmp文件然后......

$f = gzopen($filename,"r");
$content = gzread($filename,250000);
gzclose($f);

....但是男人,必须有更好的方式。

编辑:这不是一个文件,而是一个由Web服务器返回的gzip压缩页面。

有帮助吗?

解决方案

我使用curl和:

curl_setopt($ch,CURLOPT_ENCODING , "gzip");

其他提示

多功能GUNZIP功能:

   function gunzip($zipped) {
      $offset = 0;
      if (substr($zipped,0,2) == "\x1f\x8b")
         $offset = 2;
      if (substr($zipped,$offset,1) == "\x08")  {
         # file_put_contents("tmp.gz", substr($zipped, $offset - 2));
         return gzinflate(substr($zipped, $offset + 8));
      }
      return "Unknown Format";
   }  

使用CURL集成函数的示例:

      $headers_enabled = 1;
      curl_setopt($c, CURLOPT_HEADER,  $headers_enabled)
      $ret = curl_exec($c);

      if ($headers_enabled) {
         # file_put_contents("preungzip.html", $ret);

         $sections = explode("\x0d\x0a\x0d\x0a", $ret, 2);
         while (!strncmp($sections[1], 'HTTP/', 5)) {
            $sections = explode("\x0d\x0a\x0d\x0a", $sections[1], 2);
         }
         $headers = $sections[0];
         $data = $sections[1];

         if (preg_match('/^Content-Encoding: gzip/mi', $headers)) {
            printf("gzip header found\n");
            return gunzip($data);
         }
      }

      return $ret;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top