Google Translate API and Character Encoding
google-translate, json, php
Solution
if `json_decode` fails (for any reason, including charset-problems) it will return `null`, so you could check for that. to specifically chck the encoding, you could use `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
}
}
Problem
I am using the below PHP code with Google's Translate API and I have read that `json_encode` requires UTF-8 input, so was wondering how do I know if Google is returning UTF-8 encoded characters to me? ``` // 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); ```