Home > php教程 > php手册 > body text

php处理json时中文问题的解决方法

WBOY
Release: 2016-06-06 20:36:38
Original
1096 people have browsed it

最近在项目里面用到json操作,之前测试都是很正常的,不过今天在把对象转换成json的时候,其中有个中文属性变成了null.

操作的代码如下:
代码如下:
$usr = new User();
echo json_encode($usr);
?>

很简单的代码,无中文情况一切正常,输出如下:
{"PlatformID":"123213","UserID":"1023"}
一旦有中文的时候会出现两种情况。

第一种情况是对象本身的某个值为中文的属性是utf-8编码,则会有如下输出:


{"PlatformID":"123213","UserID":"1023","UserName":"\u00b7\u00f0\u00b5\u00b2\u00c9\u00b1\u00b7\u00f0\u00cc\u00fc"}
其中的UserName是非人类语言,这个是正常的,如果我们用firebug看下就是中文的。(这个纠结了我半天)

第二种情况是非utf-8编码,输出会变成null:

{"PlatformID":"123213","UserID":"1023","UserName":null}
很奇怪,查了手册后知道json_encode是只对utf-8有效,其它编码均会变为null.


下面就开始解决编码转化的问题。
在php.net上看到别人的函数如下:
代码如下:
private function to_utf8($in)
{
if (is_array($in)) {
foreach ($in as $key => $value)
{
$out[$this->to_utf8($key)] = $this->to_utf8($value);
}
}
elseif(is_string($in))
{
if(mb_detect_encoding($in) != "UTF-8")
return utf8_encode($in);
else
return $in;
}
else
{
return $in;
}
return $out;
}

于是拿下来转换编码发现已经不为null.欣喜之下用firebug打开,发现并不是我原来的中文字符....开始纠结......
难道是要让他转换成原来的编码?回去寻找原始编码......
测试开始:

1.把$usr->UserName直接输出,页面头设置charset=utf-8.乱码
2.echo json_encode($usr)输出UserName=null
3.页面头设置为charset=gbk,输出正确->可以确定原编码为gbk
最后通过IE,Chrome,Firefox测试得出结论:


1.保证页面字符集与数据库一致,输出一定正常 。
2.做json_encode时保证数据编码是utf-8,json_decode正常。
3.如果要对非utf-8字符做json_encode,先转换成utf-8。
4.对非utf-8字符做json_decode的时候,千万不能忘记转换成原先的编码,否则会输出乱码!!
困扰了一天的问题终于搞定了。
Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!