【问题标题】:file_get_contents and invalid characterfile_get_contents 和无效字符
【发布时间】:2012-04-29 19:31:36
【问题描述】:

我正在尝试使用 file_get_contents() 从 stackoverflow api 获取 json 响应,但返回给我一些奇怪的字符,例如 I–%&/mÊ{JõJ×àt¡€$Ø@ìÁˆÍæ'ìiG#)«*ÊeVe]f@ 等...

好的,地址是 http://api.stackoverflow.com/1.1/users/779187/

我的代码是

$json_res = json_decode(file_get_contents("http://api.stackoverflow.com/1.1/users/779187/")) 显然 json_dec 的响应为 NULL,因为字符串不是 json。 我也试过不带json_decode直接dump value,结果是"I–%&/mÊ{JõJ×àt¡€`$..."

感谢帮助

【问题讨论】:

    标签: php json


    【解决方案1】:

    使用gzdecode 解码压缩内容。如果您没有 gzdecode 功能,您应该使用来自this page 的实现。我已检查它是否适用于您要检索的页面。

    【讨论】:

      【解决方案2】:

      API 响应是 GZIP 格式的。请参阅此页面以解码响应:http://api.stackoverflow.com/1.1/usage/gzip

      如果切换到 cURL,则可以使用 CURLOPT_ENCODING 选项对其进行解码。

      $url = 'http://api.stackoverflow.com/1.1/users/779187/';
      $ch = curl_init(); 
      curl_setopt($ch, CURLOPT_URL, $url); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
      curl_setopt($ch, CURLOPT_ENCODING, 1);
      $output = curl_exec($ch); 
      $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
      curl_close($ch); 
      if($status=='200') {
          $data = json_decode($output);
          echo '<pre>' . print_r($data,true) . '</pre>';
      }
      

      【讨论】:

      • 感谢 Jamie,这是一个优雅的解决方案,但 cURL 在我想要实现此功能的主机(很无聊)上不活动。当然,我会在 cURL 处于活动状态的地方使用它。
      【解决方案3】:

      先用gzinflate解压。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-22
        • 2018-04-20
        • 1970-01-01
        相关资源
        最近更新 更多