解压缩gzip压缩的http响应

Fab*_*uda 15 php

我正在使用php的file_get_contents()函数来执行HTTP请求.为了节省带宽,我决定使用添加"Accept-Encoding: gzip"标头stream_context_create().

显然,file_get_contents()输出一个gzip编码的字符串,所以我gzuncompress()用来解码编码的字符串,但我得到一个错误,数据作为参数传递.

[...] PHP Warning: gzuncompress(): data error in /path/to/phpscript.php on line 26
Run Code Online (Sandbox Code Playgroud)

我知道还有另一个功能可以解压缩gzip压缩数据gzdecode()但它不包含在我的PHP版本中(可能只在SVN上可用).

我知道cUrl动态解码gzip流(没有任何问题),但有人建议我使用file_get_contents()而不是cUrl.

你知道在PHP中解压缩gzip压缩数据的任何其他方法或为什么gzuncompress()输出警告?荒谬的是gzuncompress()不能按预期工作.

注意:问题当然是关于PHP:HTTP请求是针对Tumblr API提供的,它提供了良好编码的响应.

Mik*_*ike 30

发现这对我有用:http://www.php.net/manual/en/function.gzdecode.php#106397

可选择尝试:http://digitalpbk.com/php/file_get_contents-garbled-gzip-encoding-website-scraping

if ( ! function_exists('gzdecode'))
{
    /**
     * Decode gz coded data
     * 
     * http://php.net/manual/en/function.gzdecode.php
     * 
     * Alternative: http://digitalpbk.com/php/file_get_contents-garbled-gzip-encoding-website-scraping
     * 
     * @param string $data gzencoded data
     * @return string inflated data
     */
    function gzdecode($data) 
    {
        // strip header and footer and inflate

        return gzinflate(substr($data, 10, -8));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 美丽,我一直在寻找这个 (2认同)

mar*_*rio 13

gzuncompress不适用于gzip编码.这是.Z档案的解压缩功能.

手册列出了缺少gzdecode()#82930的一些解决方法,或者只使用了一个upgradephp或gzopen临时文件解决方法.

另一种选择是deflate使用Accept-Encoding:标头强制编码,然后使用gzinflate()解压缩.