3

I got a problem. I use json_encode and after I upload on a database. My files are in utf8 and my database too. But in my database there is some \u00e9 and I don't know why ...

EDIT :

There is a simple code :

$toast = array();
    for($i=0;$i<11;$i++)
        $toast[]='é';

    $toast = json_encode($toast);
    print utf8_decode($toast);

This doesn't work how can I print a simple array full of 'é' character...

EDIT 2 :

This code :

$toast = array();
    for($i=0;$i<11;$i++)
        $toast[]='é';

    $toast = json_encode($toast);
    print $toast;

OUTPUT:

["\u00e9","\u00e9","\u00e9","\u00e9","\u00e9","\u00e9","\u00e9","\u00e9","\u00e9","\u00e9","\u00e9"]

And I want :

["é","é","é","é","é","é","é","é","é","é","é"]
2
  • 1
    there is no problems with that, those are unicodes, those are used so that some characters are escaped Commented Oct 22, 2014 at 14:34
  • they are escaped by the function? there is no solution for have é instead of \u00e9 in database Commented Oct 22, 2014 at 14:36

1 Answer 1

7

You can use JSON_UNESCAPED_UNICODE flag of json_encode (available since PHP 5.4):

$toast = json_encode($toast, JSON_UNESCAPED_UNICODE);

Before PHP 5.4, you can use this snippet:

$toast = json_encode($toast);
$toast = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function($matches) {return mb_convert_encoding(pack('H*', $matches[1]), 'UTF-8', 'UTF-16');}, $toast);

As mb_convert_encoding() is not available on all installations, you can also use this dirty workaround:

$toast = array_map('htmlentities', $toast);
$toast = json_encode($toast);
$toast = html_entity_decode($toast);

But there is no problem with \uXXXX values - it just looks uglier.

Sign up to request clarification or add additional context in comments.

7 Comments

I make this : $toast = json_encode($toast); $toast = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function($matches) {return mb_convert_encoding(pack('H*', $matches[1]), 'UTF-8', 'UTF-16');}, $toast); echo $toast; But there is no echo ...
You can use var_dump(json_last_error()) after this call to track your JSON errors.
Added a third solution :)
Seems like your error_reporting is misconfigured on your development server. Please try the third solution.
OUTPUT OF THIRD SOLUTION : ["é","é","é","é","é","é","é","é","é","é","é"]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.