Question

I've got the following script which sends some text to the Google Translate API to translate into Japanese:

    <?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'];
    ?>

However this returns 世界ã“ã‚“ã«ã¡ã¯ï¼

I'm assuming this is an encoding issue but I'm not sure how to solve this issue. The PHP manual says "This function only works with UTF-8 encoded strings."

My question is, how do I get the returned translate results to properly display?

Thanks

Était-ce utile?

La solution

The JSON contains UTF-8 encoded text, but you need to tell the browser your page uses UTF-8 encoding. Based on your output, it appears that the unicode text is being interpreted as ASCII text.

You can add the following to your PHP code to set the content type via HTTP headers:

header('Content-Type: text/html; charset=UTF-8');

And/Or, you can add a meta tag within your <head> tags to specify UTF-8:

<!-- html4/xhtml -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<!-- HTML5 -->
<meta charset="utf-8">

Autres conseils

Make sure to have the <meta charset="utf-8"> tag on your html header

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top