用于外来字符的PHP json_decode

时间:2014-05-13 05:49:55

标签: php google-translate

我已经有以下脚本将一些文本发送到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手册说&#34;此功能仅适用于UTF-8编码的字符串。&#34;

我的问题是,如何让返回的翻译结果正确显示?

由于

2 个答案:

答案 0 :(得分:2)

JSON包含UTF-8编码文本,但您需要告诉浏览器您的页面使用UTF-8编码。根据您的输出,似乎unicode文本被解释为ASCII文本。

您可以将以下内容添加到PHP代码中,以通过HTTP标头设置内容类型:

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

答案 1 :(得分:0)

确保html标题上有<meta charset="utf-8">标记