PHP json_encode utf-8 error in database
I have a problem. I am using json_encode
and after uploading to the database. My files are in utf8 and in my database. But there are several in my database \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);
It 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"]
I want too:
["é","é","é","é","é","é","é","é","é","é","é"]
source to share
You can use a flag (available as of PHP 5.4): JSON_UNESCAPED_UNICODE
json_encode
$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);
Since mb_convert_encoding()
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 the values \uXXXX
- it just looks uglier.
source to share