简体   繁体   English

php json_encode 将 utf8 字符串转换为字符代码

[英]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.然后,当我使用json_encode()将其转换为 JSON 时,我得到了一系列转义字符代码,例如 ,这似乎是一个合理的过程。 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?我应该如何在 PHP 中做到这一点?

Should I use anything of mb_* family?我应该使用 mb_* 系列的任何东西吗? I also have checked json_encode() parameters and have found nothing appropriate for me.我还检查了json_encode()参数,但没有找到适合我的参数。

UPDATE what I get saved in my DB is: ["u0633u0631u0645u0627"]更新我在数据库中保存的内容是:["u0633u0631u0645u0627"]

Which shows the characters are not escaped properly.这表明字符没有正确转义。 While if I change it to ["\س\ر\م\ا"] it becomes easily readable by json_decode()而如果我将其更改为["\س\ر\م\ا"]它变得很容易被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:如果您确定 UTF8 端到端的一切都是安全的,您可以执行以下操作:

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

http://php.net/manual/en/function.json-encode.php 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.也许尝试编码unicode字符,然后json_encoding它,然后在另一端(接收JSON)解码json,然后解码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它的简单只是使用 JSON_UNESCAPED_SLASHES 属性你的问题不是 utf8 你需要强制 JSON 不要逃避斜线

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如果你在你的 MYSQL 数据库中检查结果,它会在你没有使用的时候发生 使用 addedlashes() 示例

$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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