Home > Article > Backend Development > Solution to Chinese display problem in PHP JSON format, _PHP tutorial
The problem of Chinese display of returned json data
In the previous article, the Chinese returned in json format is displayed as u5723u8bdeu8282u5343u4e07u597du793cu5927u5949u9001
Solution 1:
Copy code The code is as follows:
function Notice(){
Include './include/conn.php'; //Database link file
$sql_notice = mysql_query('SELECT * FROM gg_notice where enable = "1" limit 0,10');
$notice = mysql_fetch_array($sql_notice, MYSQL_ASSOC);
$str = json_encode($notice);
//linux
return preg_replace("#\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\1')) ", $str);
//windows
//return preg_replace("#\u([0-9a-f]{4})#ie", "iconv('UCS-2LE', 'UTF-8', pack('H4', '\1' ))", $str);
}
?>
Other methods searched from the Internet
Copy code The code is as follows:
/**
* json generation, analysis supports Chinese
*/
class Json_Helper {
/**
* Generate json
*/
Public static function encode($str){
$json = json_encode($str);
//linux
return preg_replace("#\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\1')) ", $json);
//windows
//return preg_replace("#\u([0-9a-f]{4})#ie", "iconv('UCS-2LE', 'UTF-8', pack('H4', '\1' ))", $json);
}
/**
* Analyze json
*/
Public static function decode($str) {
return json_decode($str);
}
}
?>
This is another related article found from online search
When using the json_encode that comes with PHP to encode the data, the Chinese will become unicode, making it unreadable. For example: after json_encoding the string "Xiamen", the output is "u53a6u95e8".
After checking, there are two methods:
1. Restore "u53a6u95e8" to "Xiamen", use the following code:
Copy code The code is as follows:
$str= preg_replace("#\u([0-9a-f] )#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\1'))" , $str);
2. First urlencode and json_encode the Chinese field, and then use urldecode to display Chinese.
Copy code The code is as follows:
$code = urldecode(json_encode(urlencode("Xiamen")));
PHP version 5.4 has added a new option to Json: JSON_UNESCAPED_UNICODE. After adding this option, Chinese will not be automatically encoded.
Copy code The code is as follows:
echo json_encode("Xiamen", JSON_UNESCAPED_UNICODE);
In addition, since json_encode and json_decode only support UTF-8 encoded characters, GBK characters must be converted to JSON. Attached is the GBK to UTF-8 conversion code I wrote:
Copy code The code is as follows:
/*
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"));