简体   繁体   中英

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

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM