2013-12-14 2 views
2

최근에 웹 서비스에서 API 응답을 가져오고 디코딩하려고했습니다. 나는 단지 file_get_contents 다음에 json_decode 결과 문자열이 작동해야한다고 생각.file_get_contents에서 json_decode 문자열을 가져 오지 못했습니다.

gzip으로 처리 한 응답과 조작 된 JSON을 처리해야만 마침내 문자열을 디코딩하는 것처럼 보입니다. 어떻게 처리 할 수 ​​있습니까?

답변

2

최근 웹 서비스에서 API 응답을 가져 와서 해독하고 싶습니다. 문자열보다 및 문자열 이상을 발견했습니다. gzip으로 처리 된 응답과 조작 된 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

그것은 우리가 확실히 그 같은 사실, 질문하고 자신의 질문에 대답 괜찮아요 - 우리는 당신이 분할하도록 요청하지만, 그것들은 완전하고 개별적인 질의 응답으로 완성됩니다. 질문에 대한 "대답"부분을 가져 와서 여기로 옮겼습니다. – Flexo

+1

이전 자기 QA 형식으로 불편을 끼쳐 드려 죄송합니다. 다음에 더 잘 할거야. 내 게시물을 편집 해 주셔서 감사합니다. 정말 고마워. –

2

대신 file_get_contentscurl을 사용하고 인코딩없이 페이지의 콘텐츠를 얻을 수

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


    } 
+0

글쎄 고마워, 맥스. 당신의 cURL은 실제로 작동합니다. 나는 Google 기능을 위에 쓴 마지막 몇 시간 동안 나의 문제를 봤다. 나는 stackoverflow 답변 수만 읽었지만 그들 중 누구도 작동합니다. 이전에 cURL을 시도했지만 응답이 gzipped 콘텐츠를 반환하기 때문에 전혀 작동하지 않았습니다. 아마도 curl_setopt ($ ch, CURLOPT_ENCODING, ''); 모든 것을 한 줄로 해결 한 옵션. 나는 전에 그것을 사용하지 않았다. –

+0

@ MurdaniEko 정확하게 CURLOPT_ENCODING으로 원하는 인코딩을 넣을 수 있습니다. 코드 에서처럼 인코딩을 비우고 인코딩없이 페이지를 가져올 수 있습니다. btw를 클릭하면 틱을 클릭하여 내 대답을 수락 할 수 있습니다. – max