In actual application, when there are Chinese characters, when using json_encode() directly Function will encode the Chinese characters into the form of "\u***", since php5 This problem has been solved since .4. Use the following method to solve the problem of Chinese characters being encoded. json_encode("Chinese", JSON_UNESCAPED_UNICODE)
For example: 'Xu' becomes '\u80e5' after json_encode processing, and the final The Chinese part of json is replaced with unicode encoding. What we have to solve is to convert object to 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:
<?php class myClass { public $item1 = 1; public $item2 = '中文'; function to_json() { //url编码,避免json_encode将中文转为unicode $this->item2 = urlencode($this->item2); $str_json = json_encode($this); //url解码,转完json后将各属性返回,确保对象属性不变 $this->item2 = urldecode($this->item2); return urldecode($str_json); } } $c = new myClass(); echo json_encode($c); echo '<br/>'; echo $c->to_json(); echo '<br/>'; echo json_encode($c); echo '<br/>'; echo json_encode('胥'); ?>
Program output result:
{"item1":1,"item2":"\u4e2d\u6587"} {"item1":1,"item2":"中文"} {"item1":1,"item2":"\u4e2d\u6587"} "\u80e5"
The above is the detailed content of Problem with json_encode Chinese encoding in php. For more information, please follow other related articles on the PHP Chinese website!