Home
php教程
PHP开发
Solution to the problem that php5.2 Json cannot correctly handle Chinese and GB encoding



Solution to the problem that php5.2 Json cannot correctly handle Chinese and GB encoding
php5.2新增的json功能是非常受欢迎的,但是经过测试发现,
json_encode对中文的处理是有问题的,
1.不能处理GB编码,所有的GB编码都会替换成空字符.
2.utf8编码的中文被编码成unicode编码,相当于javascript的escape函数处理的结果.
/* 为了能正确使用json,首先我们就应该在编码上采用utf8编码,然后再对json_encode的返回结果稍加处理就可以得到正确的结果了。 我写了一个简单的类,将这两个函数包装了一下, **/ class Json{ public static function encode($str){ $code = json_encode($str); return preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $code); } public static function decode($str){ return json_decode($str); } } //使用的时候 Json::encode($code); Json::decode($code); /**这样可以正确处理utf8编码的中文了。 PS:对于GB编码的中文,我们可以在编码时先转成UTF8编码,再进行编码,解码的时候再进行一个utf8 -> gb的转换就可以了。 另外一般json_encode的结果我们是返回到客户端来使用,我们其实还可以用javascript的unescape函数来对unicode编码的中文进行解码,从而还原成正确的中文。 或者用:$title = mb_convert_encoding($title, 'HTML-ENTITIES', $this->_outCharset);//任意编码下都正常显示 ********/
Copy after login
更多php5.2 Json不能正确处理中文、GB编码的解决方法相关文章请关注PHP中文网!
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

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
How to fix KB5055523 fails to install in Windows 11?
3 weeks ago
By DDD
How to fix KB5055518 fails to install in Windows 10?
3 weeks ago
By DDD
Roblox: Dead Rails - How To Tame Wolves
4 weeks ago
By DDD
Roblox: Grow A Garden - Complete Mutation Guide
2 weeks ago
By DDD
Strength Levels for Every Enemy & Monster in R.E.P.O.
4 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics
Java Tutorial
1657
14


CakePHP Tutorial
1415
52


Laravel Tutorial
1309
25


PHP Tutorial
1257
29


C# Tutorial
1230
24

