Home > Backend Development > PHP Tutorial > Solve the problem that Chinese objects in PHP are encoded into unicode after being converted using json_encode_PHP Tutorial

Solve the problem that Chinese objects in PHP are encoded into unicode after being converted using json_encode_PHP Tutorial

WBOY
Release: 2016-07-21 14:58:06
Original
1256 people have browsed it

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 ?>
Copy after login

Program output result:

{"item1":1,"item2":"\u4e2d\u6587"}<br>{"item1":1,"item2":"中文"}<br>{"item1":1,"item2":"\u4e2d\u6587"}<br>"\u80e5"
Copy after login

I hope this article can serve as a starting point and collect better solutions from everyone...!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/363894.htmlTechArticlePhenomenon: As we all know, json_encode can be used to quickly and easily json encode objects, but if there are Chinese characters in the attributes of the object , and problems arise. json_encode will hit...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template