无法从file_get_contents中获取json_decode字符串

时间:2013-12-14 14:46:29

标签: php file-get-contents json

我最近想要从Web服务获取和解码API响应。我认为只有file_get_contents然后json_decode结果字符串应该有用。

看起来我必须处理gzipped响应和格式错误的JSON才能最终解码字符串。我怎么处理这些?

2 个答案:

答案 0 :(得分:2)

最近我想从Web服务获取和解码API响应,然后发现它不仅仅是file_get_contentsjson_decode字符串。我必须处理gzipped响应和格式错误的JSON才能最终解码字符串。

经过几个小时的搜索,下面的两个功能刚刚结束了我的一天。

// 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 );
  }
}

答案 1 :(得分:2)

您可以使用curl代替file_get_contents并获取不带任何编码的网页内容

   function get_url($link){

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_VERBOSE, 0);
      curl_setopt($ch,CURLOPT_ENCODING, '');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_URL, ($link));
      $response = curl_exec($ch);
      curl_close($ch);
      return ($response); 


    }
相关问题