php中json_encode中文编码问题分析

PHPz
Release: 2018-10-08 15:30:53
forward
1613 people have browsed it

众所周知使用json_encode可以方便快捷地将对象进行json编码,但是如果对象的属性中存在着中文,问题也就随之而来了。json_encode会将中文转换为unicode编码

例如:'胥'经过json_encode处理后变为'\u80e5',最终的json中中文部分被替换为unicode编码。我们要解决的就是将对象转换为json并保证对象内部的中文在json中仍然是以正常的中文出现,现在看来只使用json_encode是不能达到目的的。

我的解决方法:先将类中的中文字段进行url编码(urlencode),然后再对对象进行json编码(jsonencode),最后url解码(urldecode)json,即最终的json,里面的中文依旧是那个中文!
测试代码如下:

代码如下:

<?php 
class myClass { 
public $item1 = 1; 
public $item2 = &#39;中文&#39;; 
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 &#39;<br/>&#39;; 
echo $c->to_json(); 
echo &#39;<br/>&#39;; 
echo json_encode($c); 
echo &#39;<br/>&#39;; 
echo json_encode(&#39;胥&#39;); 
?>
Copy after login

程序输出结果:

代码如下:

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

希望本文起到抛砖引玉的作用,收集大家更好的解决方法……!

更多相关教程请访问 php编程从入门到精通全套视频教程

 

Related labels:
source:jb51.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!