为什么PHP json_encode 函数会将UTF-8 字符串转换为十六进制实体?

2021-12-27 00:00:00 json encoding php

我有一个处理多种语言的 PHP 脚本.不幸的是,每当我尝试使用 json_encode 时,任何 Unicode 输出都会转换为十六进制实体.这是预期的行为吗?有没有办法将输出转换为UTF-8字符?

I have a PHP script that deals with a wide variety of languages. Unfortunately, whenever I try to use json_encode, any Unicode output is converted to hexadecimal entities. Is this the expected behavior? Is there any way to convert the output to UTF-8 characters?

以下是我所看到的示例:

Here's an example of what I'm seeing:

输入

echo $text;

输出

База данни грешка.

输入

json_encode($text);

输出

"u0411u0430u0437u0430 u0434u0430u043du043du0438 u0433u0440u0435u0448u043au0430."

推荐答案

自 PHP/5.4.0 起,有一个名为 JSON_UNESCAPED_UNICODE 的选项.看看:

Since PHP/5.4.0, there is an option called JSON_UNESCAPED_UNICODE. Check it out:

https://php.net/function.json-encode

因此您应该尝试:

json_encode( $text, JSON_UNESCAPED_UNICODE );

相关文章