Home > Backend Development > PHP Tutorial > php5.2 Json cannot correctly handle Chinese and GB encoding solutions_PHP tutorial

php5.2 Json cannot correctly handle Chinese and GB encoding solutions_PHP tutorial

WBOY
Release: 2016-07-13 10:35:03
Original
783 people have browsed it

The new json function of php5.2 is very popular, but after testing, it was found that
json_encode has problems with Chinese processing.
1. It cannot handle GB encoding, and all GB encodings will be replaced with empty Character.
2.utf8 encoded Chinese is encoded into unicode encoding, which is equivalent to the result of JavaScript's escape function processing.

Copy code The code is as follows:

/*

In order to use json correctly, first we should use utf8 encoding for encoding, and then slightly process the return result of json_encode to get the correct result .
I wrote a simple class to wrap these two functions,
**/
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);
}
}
//When used

Json::encode($code);
Json::decode($code);
/**This can correctly handle utf8 encoded Chinese.

PS: For GB-encoded Chinese, we can first convert to UTF8 encoding when encoding, then encode, and then perform a utf8 -> gb conversion when decoding.
In addition, we generally return the results of json_encode to the client for use. We can actually use the unescape function of JavaScript to decode the unicode-encoded Chinese and restore it to the correct Chinese.

Or use: $title = mb_convert_encoding($title, 'HTML-ENTITIES', $this->_outCharset);//It will be displayed normally in any encoding
********/

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/746869.htmlTechArticleThe new json function of php5.2 is very popular, but after testing, it was found that json_encode’s processing of Chinese There are problems, 1. GB encoding cannot be processed, all GB encodings will be replaced with empty...
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