In php, the json_decode() function can convert arrays to json format data. However, the json_decode() function only supports UTF-8 and ASCII encoding. If it is gkb, there will be problems. Let's take a look at the problem analysis. with solutions.
It seems that when using json_decode() to serialize an array/object into a JSON string, it basically only supports UTF-8/ASCII encoding. Some of our sites use GBK/GB2312 encoding. At this time, problems may occur when using json_encode/json_decode directly.
The code is as follows
代码如下 |
复制代码 |
$json = '{"a":"中国人人"}';
var_dump(json_decode($json));
?>
结果
{"text":null,"status":1}
|
|
Copy code
|
代码如下 |
复制代码 |
/*
字符串GBK转码为UTF-8,数字转换为数字。
*/
function ct2($s){
if(is_numeric($s)) {
return intval($s);
} else {
return iconv("GBK","UTF-8",$s);
}
}
/*
批量处理gbk->utf-8
*/
function icon_to_utf8($s) {
if(is_array($s)) {
foreach($s as $key => $val) {
$s[$key] = icon_to_utf8($val);
}
} else {
$s = ct2($s);
}
return $s;
}
echo json_encode(icon_to_utf8("厦门"));
|
$json = '{"a":"中国人人"}';
var_dump(json_decode($json));
?> |
Results
{"text":null,"status":1}
For example, when converting characters containing Chinese characters into null (null), but sometimes we have to use gb encoding and use json_decode() for conversion? What to do? Last night I wrote a small background for adding music without using a database. That is, use php to add music and then generate an xml menu. If you don't use a database, you have to use a way to save the data. The data saved as text can be used directly. I think it is to use json_decode() to convert the array into json format. When used, it can be taken out and used to json_encode to convert it back to the array (maybe js has been replaced by json recently. Affected, it seems that there are better ways to serialize arrays, such as using: serialize() and unserialize()), haha, let’s get back to the topic. Since json_decode() cannot convert Chinese in gb encoding, we can first convert Chinese into English encoding. Then you can use this urlencode() to convert the encoding, and then do json_decode() conversion. When using it, just use urldecode() to convert it to Chinese
The code is as follows
|
Copy code
/*
GBK string transcoding is converted to UTF-8, and numbers are converted to numbers.
*/
function ct2($s){
If(is_numeric($s)) {
return intval($s);
} else {
return iconv("GBK","UTF-8",$s);
}
}
/*
Batch processing gbk->utf-8
*/
function icon_to_utf8($s) {
if(is_array($s)) {
foreach($s as $key => $val) {
$s[$key] = icon_to_utf8($val);
}
} else {
$s = ct2($s);
}
return $s;
}
echo json_encode(icon_to_utf8("Xiamen"));
http://www.bkjia.com/PHPjc/632733.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632733.htmlTechArticleIn php, the json_decode() function can convert arrays to json format data, but the json_decode() function only Supports UTF-8 and ASCII encoding. If it is gkb, there will be problems. Let's take a look...
|
|