dream0776 2013-12-14 14:46
浏览 357

无法从file_get_contents中获取json_decode字符串

I recently wanted to fetch and decode API response from a web service. I thought that just just file_get_contents and then json_decode the resulting string should work.

It looks like I have to deal with gzipped response and malformed JSON to finally decode the string. How can I handle these?

  • 写回答

2条回答 默认 最新

  • dp20011 2013-12-14 14:46
    关注

    Recently I wanted to fetch and decode API response from a web service, then found out that it was a lot more than just file_get_contents and json_decode the string. I have to deal with gzipped response and malformed JSON to finally decode the string.

    After hours of searching, both functions below had just saved my day.

    // http://stackoverflow.com/questions/8895852/uncompress-gzip-compressed-http-response
    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));
    }
    }
    
    
    /**
     * Fetch the requested URL and return it as decoded json object
     * 
     * @author string  Murdani Eko
     * @param  string  $url
     */
    function get_json_decode( $url ) {
    
      $response = file_get_contents( $url );
      $response = trim( $response );
    
      // is it a valid json string?
      $jsondecoded = json_decode( $response );
      if( json_last_error() == JSON_ERROR_NONE ) {
        return $jsondecoded;
      }
    
      // yay..! it's a gzencoded string
      if( json_last_error() == JSON_ERROR_UTF8 ) {
        $response = gzdecode($response);
    
        /* After gzdecoded, there is a chance that the response 
         * will have extra character after the curly brackets e.g. }}gi or }} ee
         * This will cause malformed JSON, and later failed json decoding
         */
    
        // we search-reverse the closing curly bracket position
        $last_curly_pos = strrpos($response, '}');
        $last_curly_pos++; 
    
        // extract the correct json format using the last curly bracket position
        $good_response = substr($response, 0, $last_curly_pos);
    
        return json_decode( $good_response );
      }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度