Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Translate API and Character Encoding

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);
like image 625
Brett Avatar asked Dec 01 '25 22:12

Brett


1 Answers

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
  }
}
like image 77
oezi Avatar answered Dec 03 '25 13:12

oezi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!