【问题标题】:How can I read GZIP-ed response from Stackoverflow API in PHP?如何在 PHP 中读取来自 Stackoverflow API 的 GZIP 版响应?
【发布时间】:2011-12-20 21:01:25
【问题描述】:

如何在 PHP 中读取来自 Stackoverflow API 的响应?响应是 GZIP 格式的。我发现例如以下建议:

$url = "http://api.stackoverflow.com/1.1/questions/" . $question_id;
$data = file_get_contents($url);
$data = http_inflate($data);

但是http_inflate() 功能在我正在使用的安装中不可用。

还有其他简单的方法可以实现吗?

【问题讨论】:

    标签: php gzip


    【解决方案1】:

    一个很酷的方法 http://www.php.net/manual/en/wrappers.compression.php

    注意流包装器的使用,compress.zlib

    $url = "compress.zlib://http://api.stackoverflow.com/1.1/questions/" . $question_id; 
    echo $data = file_get_contents($url, false, stream_context_create(array('http'=>array('header'=>"Accept-Encoding: gzip\r\n"))));
    

    或使用 curl

    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url
      , CURLOPT_HEADER => 0
      , CURLOPT_RETURNTRANSFER => 1
      , CURLOPT_ENCODING => 'gzip'
    ));
    echo curl_exec($ch);
    

    已编辑-- 其他方法已删除,因为它们不发送 Accept-Encoding http 标头。

    【讨论】:

    • 这确实有效!我之前也试过compress.zlib,但没有正确格式化完整的url。谢谢(+1)!
    • 轻松最好的方法(流包装器)
    • @chris: gzopen() 也可以。您的 3 种方法在性能上是否存在差异?
    • 我不确定,但我的钱在流包装器 + file_get_contents
    • 谢谢兰博,这很有帮助!
    【解决方案2】:

    使用它来获取 gzip 编码 json 响应,它的工作就像一个魅力

    function get_gzip_json($url) {
     $ch = curl_init();
     curl_setopt_array($ch, array(
       CURLOPT_URL => $url,
       CURLOPT_HEADER => 0,
       CURLOPT_RETURNTRANSFER => 1,
       CURLOPT_ENCODING => 'gzip',
     ));
    
     $json = curl_exec($ch);
     $json= mb_convert_encoding($json, "UTF-8", "UTF-8"); 
    
     return $json;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-10
      • 1970-01-01
      • 2015-10-31
      • 2015-01-26
      • 2018-12-16
      • 2013-01-16
      • 1970-01-01
      相关资源
      最近更新 更多