Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

php - Failed to json_decode string from file_get_contents

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...