Home  >  Article  >  php教程  >  Solution to json_encode in php to deal with gbk and gb2312 Chinese garbled problems

Solution to json_encode in php to deal with gbk and gb2312 Chinese garbled problems

高洛峰
高洛峰Original
2016-12-27 16:15:121873browse

This article describes how json_encode in php handles the Chinese garbled problem of gbk and gb2312. 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}]

Have you taken a look? "meta_title":null He originally had One value is "Script Home". We checked 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(&#39;name&#39;=>&#39;中文字符串&#39;,&#39;value&#39;=>&#39;test&#39;);
echo json_encode($testJSON);
?>

View the output result as:

{"name":"u4e2du6587u5b57u7b26u4e32″,"value":"test"}

It can be seen that UTF8 encoding is used characters, Chinese garbled characters also 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(&#39;name&#39;=>&#39;中文字符串&#39;,&#39;value&#39;=>&#39;test&#39;);
//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: json_encode function It 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.

For more related articles on how json_encode in PHP handles gbk and gb2312 Chinese garbled problems, please pay attention to the PHP Chinese website!

Statement:
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