2012-05-05 2 views
3

Google의 Translate API와 함께 아래 PHP 코드를 사용하고 있으며 json_encode에 UTF-8 입력이 필요하다는 것을 읽었으므로 Google에서 UTF-8 인코딩 된 문자를 반환하는지 어떻게 알 수 있는지 궁금합니다. ? json_decode이 실패 할 경우Google 번역 API 및 문자 인코딩

// URL Encode string 
$str = urlencode($str); 

// Make request 
$response = file_get_contents('https://www.googleapis.com/language/translate/v2?key=' . GTRAN_KEY . '&target=es&source=en&q=' . $str); 

// Decode json response to array 
$json = json_decode($response,true); 

답변

4

(캐릭터-문제를 포함하여 어떤 이유에 대한)이 null를 반환합니다, 그래서 당신은 그것에 대해 확인할 수 있습니다. 특히 인코딩을 chck하려면 mb_detect_encoding을 사용할 수 있습니다.

if(!mb_detect_encoding($response, 'UTF-8', true)){ 
    // error: no utf-8 
}else{ 
    $json = json_decode($response,true); 
    if($json === null){ 
    // error: json_decode failed (or google returned 'null') 
    }else{ 
    // ok, do great stuff here 
    } 
} 
+0

대단히 감사합니다. – Brett