Google Translate API and character encoding

I use the PHP code below with the Google Translate API, and I read that it json_encoderequires UTF-8 input, so I was wondering how do I know if Google returns me UTF-8 encoded characters?

// 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);
+3
source share
1 answer

if json_decodeit fails (for any reason, including problems with the character set), it will return null, so you can check it, you can use it for special encoding of the encoding 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
  }
}
+4
source

All Articles