Home > Article > Backend Development > Solution to json_encode in php to deal with gbk and gb2312 Chinese garbled problems, _PHP tutorial
This article describes the solution to the problem of gbk and gb2312 Chinese garbled characters in json_encode in php. The specific method is as follows:
1.json_encode() Chinese returns null for Chinese in gbk/gb2312
$arr = array ( array ( 'catid' => '4', 'catname' => 'www.jb51.net', 'meta_title' => '帮客之家' ) ); echo json_encode($arr);
Run result:
[{"catid":"4","catname":"www.jb51.net","meta_title":null}]
Did you take a look at "meta_title":null? It originally had a value of "Bangkejia". We checked this and the principle is that json_encode only supports uft-8 encoding. Let's convert it
<?php $data="JSON中文"; $newData=iconv("GB2312″,"UTF-8//IGNORE",$data); echo $newData; //ignore的意思是忽略转换时的错误,如果没有ignore参数,所有该字符后面的字符都不会被保存。 //或是("GB2312″,"UTF-8″,$data); ?>
2. The background PHP page (the page is encoded as UTF-8 or the characters have been converted to UTF-8) uses json_encode to convert the array array in PHP into a JSON string. For example:
<?php $testJSON=array('name'=>'中文字符串','value'=>'test'); echo json_encode($testJSON); ?>
View the output result:
{"name":"u4e2du6587u5b57u7b26u4e32″,"value":"test"}
It can be seen that even if UTF8-encoded characters are used, Chinese garbled characters appear when using json_encode. The solution is to process the characters with the function urlencode() before using json_encode, then json_encode, and then use the function urldecode() to convert them back when outputting the result. The details are as follows:
<?php $testJSON=array('name'=>'中文字符串','value'=>'test'); //echo json_encode($testJSON); foreach ( $testJSON as $key => $value ) { $testJSON[$key] = urlencode ( $value ); } echo urldecode ( json_encode ( $testJSON ) ); ?>
View the output result:
{"name":"中文字符串","value":"test"}
Summary: The json_encode function can only process uft8 strings. If it is Chinese, it probably does not handle bytes well, because the lengths of Chinese gbk and uft are different . This will not be introduced in depth. .