PHP json_decode 外来字符

标签 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 手册说“此函数仅适用于 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/

相关文章:

google-translate - Google Translate API 定价和语言自动检测效率

php - Mysql 查询从没有记录的连接计数为零

php - Symfony2 Profiler 数据库面板中的空结果

php - 将数据发送到 Laravel 5.8 中的 View 时 undefined variable

php - 删除 WooCommerce 评论选项卡上的 (0)

css - 你能设计谷歌翻译插件吗?

php - 在 mysql 中,一行总是在最上面

javascript - Bootstrap 模式中的 TinyMCE 与谷歌翻译冲突

java - 在 Android 应用程序中使用谷歌翻译

javascript - google.language API 不再可用