简体   繁体   English

谷歌翻译API和字符编码

[英]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? 我使用下面的PHP代码与谷歌的Translate API,我已经读过json_encode需要UTF-8输入,所以我想知道如何知道谷歌是否向我返回UTF-8编码字符?

// 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. 如果json_decode失败(由于任何原因,包括charset-problems),它将返回null ,因此您可以检查它。 to specifically chck the encoding, you could use mb_detect_encoding . 要专门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
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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