我有以下脚本,它将一些文本发送到 Google Translate API 以翻译成日语:
<?php
$apiKey = 'myApiKey';
$text = 'Hello world!';
$url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=ja';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
echo 'Source: ' . $text . '<br>';
echo 'Translation: ' . $responseDecoded['data']['translations'][0]['translatedText'];
?>
但是这会返回世界ã“ã‚”ã«ã¡ã̄ï¼
我假设这是一个编码问题,但我不确定如何解决这个问题。 PHP 手册说“此函数仅适用于 UTF-8 编码的字符串。”
我的问题是,如何让返回的翻译结果正确显示?
谢谢
最佳答案
JSON 包含 UTF-8 编码文本,但您需要告诉浏览器您的页面使用 UTF-8 编码。根据您的输出,unicode 文本似乎被解释为 ASCII 文本。
您可以将以下内容添加到 PHP 代码中,以通过 HTTP header 设置内容类型:
header('Content-Type: text/html; charset=UTF-8');
和/或者,您可以在 <head>
中添加元标记指定 UTF-8 的标签:
<!-- html4/xhtml -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- HTML5 -->
<meta charset="utf-8">
关于PHP json_decode 外来字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23623660/