Solution is missing when using json_decode () on the GBK/GB2312 page in php

Source: Internet
Author: User
Tags php and

It seems that only UTF-8/ASCII encoding is supported when arrays/objects are serialized as JSON strings with json_decode. Some of our sites use GBK/GB2312 encoding. In this case, problems may occur when json_encode/json_decode is used directly.

The code is as follows: Copy code

<? Php
$ Json = '{"a": ""}';
Var_dump (json_decode ($ json ));
?>

Result

{"Text": null, "status": 1}

For example, if the conversion of characters containing Chinese characters becomes null, but sometimes we have to use gb encoding and json_decode () conversion? What should I do? I wrote a small background for adding music without using a database last night. That is, add music using php and then generate an xml menu. You can save the data in one way without using a database. The data saved as text can be used out directly. I think it is used to convert the array json_decode () into json format, you can use json_encode to convert it back to an array. (it may be affected by json recently. It seems that there are better methods to serialize the array. For example, use: serialize () and unserialize. Since json_decode () cannot be converted to Chinese in gb encoding, we can convert Chinese into English encoding first. You can use this urlencode () to convert the code and then perform the json_decode () conversion. You can use urldecode () to convert it to Chinese.

The code is as follows: Copy code

/*
The string GBK is transcoded to a UTF-8, and the number is converted to a number.
*/
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 "));

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.