PHP does not escape Chinese characters when using the json_encode function,
This example describes how to avoid escaping Chinese characters when using the json_encode function in PHP. Share it with you for your reference. The specific method is as follows:
The json_encode function does not convert Chinese Characters in gbk or directly convert them into spaces. This article will help you solve the problem of json not escaping Chinese characters.
If you call the json_encode () function that comes with PHP, when you encounter a Chinese character, the Chinese character will be escaped. For example:
Copy codeThe Code is as follows: echo json_encode (array (' '));
// Output: ["\ u4f60 \ u597d"]
This is very annoying, like a bunch of garbled characters. The JSON standard never says that non-ASCII characters should be escaped. The standard is "Any UNICODE character ".
How can I disable this escape? The answer is: PHP's built-in json_encode () cannot disable this feature (you can add the JSON_UNESCAPED_UNICODE option for later versions before version 5.4.0). You can only change to a new JSON library. for simplicity, I wrote dozens of lines of code to implement a json_encode ().
Copy codeThe Code is as follows: class Util
{
Static function json_encode ($ input ){
// This option has been added since PHP 5.4.0.
If (defined ('json _ UNESCAPED_UNICODE ')){
Return json_encode ($ input, JSON_UNESCAPED_UNICODE );
}
If (is_string ($ input )){
$ Text = $ input;
$ Text = str_replace ('\\',' \\\\ ', $ text );
$ Text = str_replace (
Array ("\ r", "\ n", "\ t ","\""),
Array ('\ R',' \ n', '\ t ','\\"'),
$ Text );
Return '"'. $ text .'"';
} Else if (is_array ($ input) | is_object ($ input )){
$ Arr = array ();
$ Is_obj = is_object ($ input) | (array_keys ($ input )! = Range (0, count ($ input)-1 ));
Foreach ($ input as $ k => $ v ){
If ($ is_obj ){
$ Arr [] = self: json_encode ($ k). ':'. self: json_encode ($ v );
} Else {
$ Arr [] = self: json_encode ($ v );
}
}
If ($ is_obj ){
Return '{'. join (',', $ arr ).'}';
} Else {
Return '['. join (',', $ arr). ']';
}
} Else {
Return $ input .'';
}
}
}
I can't think about it, for example, judging the location of the associated array (is_obj). If you don't like the class, convert it to a pure function and change the name.
I hope this article will help you with PHP programming.