In php, after the object is converted using json_encode, the Chinese character is encoded as unicode. 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 will be abnormal: it is well known that using json_encode can easily and quickly encode the object in json format. However, if the attribute of the object contains 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!
The test code is as follows:
1
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'
';
19 echo $ c-> to_json ();
20 echo'
';
21 echo json_encode ($ c );
22 echo'
';
23 echo json_encode ('signature ');
24?>
Program output 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 ......!
Bytes. Json_encode will put...