Flying Pheonix Flying Pheonix - 5 months ago 26
PHP Question

PHP | json_decode() causing character problems

I am retrieving data from an API which is returning encoded characters. For example part of the string returned is

\u2605
which is the unicode for a special symbol (a start), see link:
http://www.fileformat.info/info/unicode/char/2605/index.htm

With php i run the following code to convert the data into an array so that i can work with it:

$result = file_get_contents($url);
$decoded = json_decode($result, true)


However, the problem i have is that the unicode codes for the symbols are then converted to some giberish. For example the
\u2605
is converted to
★
.

Other symboles are also converted.

What can I do here?

Answer

JSON is using utf-8 character encoding by default. that's why you have to output the decoded JSON in utf-8 charset as well.

If you are doing the output in html, try to set the meta-charset:

<html>
    <head>
        <meta charset="utf-8" />
    </head>
    <body>
    <?php
        $json = '{"value":"\u2605"}';
        $dec = json_decode($json);
        var_dump($dec);
    ?>
    </body>
</html>