Phenomenon: As we all know, using json_encode can quickly and easily encode objects into json, but if there are Chinese characters in the attributes of the object, problems will arise. json_encode will convert Chinese to unicode encoding. 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. Now it seems that only using json_encode cannot achieve the goal.
My solution: first url encode (urlencode) the Chinese field in the class, then json encode (jsonencode) the object, and finally url decode (urldecode) json, which is the final json, and the Chinese inside is still the same It's the Chinese one!
The test code is as follows:
1 <?php<br /> 2 class myClass {<br /> 3 public $item1 = 1;<br /> 4 public $item2 = '中文';<br /> 5 <br /> 6 function to_json() {<br /> 7 //url编码,避免json_encode将中文转为unicode<br /> 8 $this->item2 = urlencode($this->item2);<br> 9 $str_json = json_encode($this);<br>10 //url解码,转完json后将各属性返回,确保对象属性不变<br>11 $this->item2 = urldecode($this->item2);<br>12 return urldecode($str_json);<br>13 }<br>14 }<br>15 <br>16 $c = new myClass();<br>17 echo json_encode($c);<br>18 echo '<br/>';<br>19 echo $c->to_json();<br>20 echo '<br/>';<br>21 echo json_encode($c);<br>22 echo '<br/>';<br>23 echo json_encode('胥');<br>24 ?>
Program output result:
{"item1":1,"item2":"\u4e2d\u6587"}<br>{"item1":1,"item2":"中文"}<br>{"item1":1,"item2":"\u4e2d\u6587"}<br>"\u80e5"
I hope this article can serve as a starting point and collect better solutions from everyone...!