Introduction: This is a detailed page of question about json_encode in PHP. It introduces PHP, related knowledge, skills, experience, and some PHP source code.
Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 351605 'rolling = 'no'>
Symptom: It is well known that json_encode can be used to easily and quickly encode objects in JSON format. However, if the attributes of an object contain Chinese characters, the problem will arise. Json_encode converts Chinese to unicode encoding. For example, after 'encoding' is processed by json_encode, it is changed to '\ u80e5'. In the final JSON, the Chinese part is replaced with Unicode encoding. What we need to solve is to convert the object to JSON and ensure that the Chinese character inside the object still appears in JSON as normal Chinese. Now it seems that json_encode alone cannot achieve the goal.
My solution: perform URL encoding for the Chinese fields in the class first, then perform JSON encoding (jsonencode) for the object, and finally URL Decoding (urldecode) JSON, that is, the final JSON. The Chinese in it is still the Chinese!
TestCodeAs follows:
1 <? PHP
2 class myclass {
3 Public $ Item1 = 1;
4 Public $ item2 = 'Chinese ';
5
6 function to_json (){
7 // URL encoding to avoid converting Chinese to Unicode by using json_encode
8 $ this-> item2 = urlencode ($ this-> item2 );
9 $ str_json = json_encode ($ this );
10 // URL Decoding. After converting JSON, all attributes are returned to ensure that the object attributes remain unchanged.
11 $ this-> item2 = urldecode ($ this-> item2 );
12 Return urldecode ($ str_json );
13}
14}
15
16 $ c = new myclass ();
17 echo json_encode ($ C );
18 echo '<br/> ';
19 echo $ C-> to_json ();
20 echo '<br/> ';
21 echo json_encode ($ C );
22 echo '<br/> ';
23 echo json_encode ('signature ');
24?>
ProgramOutput result:
{"Item1": 1, "item2": "\ u4e2d \ u6587 "}
{"Item1": 1, "item2": "Chinese "}
{"Item1": 1, "item2": "\ u4e2d \ u6587 "}
"\ U80e5"
I hope this article will serve as a reference to collect better solutions ......!
Love J2EE follow Java Michael Jackson video station JSON online tools
Http://biancheng.dnbcw.info/php/351605.html pageno: 3