


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);//任意编码下都正常显示 ********/
更多php5.2 Json不能正确处理中文、GB编码的解决方法相关文章请关注PHP中文网!

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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

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.