解决php中对象使用json_encode转换后中文被编码为unicode
现象:众所周知使用json_encode可以方便快捷地将对象进行json编码,但是如果对象的属性中存在着中文,问题也就随之而来了。json_encode会将中文转换为unicode编码,例如:'胥'经过json_encode处理后变为'\u80e5',最终的json中中文部分被替换为unicode编码。我们要解决的就是将对象转换为json并保证对象内部的中文在json中仍然是以正常的中文出现,现在看来只使用json_encode是不能达到目的的。
我的解决方法:先将类中的中文字段进行url编码(urlencode),然后再对对象进行json编码(jsonencode),最后url解码(urldecode)json,即最终的json,里面的中文依旧是那个中文!
测试代码如下:
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 ?>
程序输出结果:
{"item1":1,"item2":"\u4e2d\u6587"}<br>{"item1":1,"item2":"中文"}<br>{"item1":1,"item2":"\u4e2d\u6587"}<br>"\u80e5"
希望本文起到抛砖引玉的作用,收集大家更好的解决方法……!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
