Home >Backend Development >PHP Tutorial >Analysis of json_encode Chinese encoding issues in json_encode php

Analysis of json_encode Chinese encoding issues in json_encode php

WBOY
WBOYOriginal
2016-07-29 08:46:431137browse

For example: 'Xu' becomes 'u80e5' after json_encode processing, and the Chinese part of the final json is replaced with unicode encoding. What we have to solve is to convert the object into json and ensure that the Chinese inside the object still appears as normal Chinese in json. It seems that only using json_encode cannot achieve the goal.
My solution: first url-encode the Chinese field in the class (urlencode), then json-encode the object (jsonencode), and finally url-decode (urldecode) the json, which is the final json. The Chinese inside is still the same Chinese!
The test code is as follows:

Copy the code The code is as follows:


class myClass {
public $item1 = 1;
public $item2 = 'Chinese';
function to_json() {
//URL encoding, avoid json_encode converting Chinese to unicode
$this->item2 = urlencode($this->item2);
$str_json = json_encode($this);
//URL decoding, after converting json Return each attribute to ensure that the object attributes remain unchanged
$this->item2 = urldecode($this->item2);
return urldecode($str_json);
}
}
$c = new myClass();
echo json_encode($c);
echo '
';
echo $c->to_json();
echo '
';
echo json_encode($c);
echo '
';
echo json_encode('胥');
?>


Program output result:

Copy code The code is as follows:


{"item1":1, "item2":"u4e2du6587"}
{"item1":1,"item2":"Chinese"}
{"item1":1,"item2":"u4e2du6587"}
"u80e5"


Hope this article will start Let’s serve as a guide and collect better solutions from everyone…!

The above introduces the analysis of json_encode Chinese encoding problems in json_encode php, including the content of json_encode. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn