php 中解决json中文乱码的函数
php教程自带了json_encode来处理json数据,那么它们对中文的支持不好,下面我们来看个实例
echo json_encode(array(123213,'中国'));
{"platformid":"123213","userid":"1023","username":"u00b7u00f0u00b5u00b2u00c9u00b1u00b7u00f0u00ccu00fc"}
我们会发现,英文可以正确解析,但中文就出来u00b7u00f0u00b5u00b2u00c9u00b1u00b7u00f0u00ccu00fc哦,这可能是unicode编码,但我没测试过只是自己猜的。下面我们来看一款解决json中文乱码的函数
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;
}
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的时候,千万不能忘记转换成原先的编码,否则会输出乱码!!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor