简体   繁体   中英

Php json_encode converts utf8 string to characters codes

I have a Persian text "سرما"

And then when I convert it to JSON using json_encode() , I get a series of escaped character codes such as which seems to be expected and of a rational process. But my confusion lies where I don't know how to convert them back into readable string of characters. How should I do that in PHP?

Should I use anything of mb_* family? I also have checked json_encode() parameters and have found nothing appropriate for me.

UPDATE what I get saved in my DB is: ["u0633u0631u0645u0627"]

Which shows the characters are not escaped properly. While if I change it to ["\س\ر\م\ا"] it becomes easily readable by json_decode()

They should be converted back on the other end when it's decoded. This is the safest option as it might not be possible to guaranteed that the transmission or storage will not corrupt a multi-byte encoding.

If you're certain that everything is safe for UTF8 end-to-end you can do:

$res = json_encode($foo, \JSON_UNESCAPED_UNICODE);

http://php.net/manual/en/function.json-encode.php

Maybe try encoding the unicode characters, and then json_encoding it, then on the other side (receiving JSON) decode the json, then decode the unicode.

Example:

//Encode
json_encode(utf8_encode($string));

//Decode
utf8_decode(json_decode($string)); 

its simple just use JSON_UNESCAPED_SLASHES atribute your problem is't utf8 you need force JSON to don't escape Slashes

example

$bar = "سرما";
$res = json_encode($bar, JSON_UNESCAPED_SLASHES );
// $res equal to ["\u0633\u0631\u0645\u0627"]

if you check the result in your MYSQL Database it happen when you did't Use addslashes() example

$bar = "سرما";
$res = json_encode($bar, JSON_UNESCAPED_SLASHES );
$res = addslashes($res);
// $res equal to ["\\u0633\\u0631\\u0645\\u0627"] now it's ready to use in MYSQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM