Many friends may encounter problems with NULL or garbled characters when using the functions JSON_DECODE/JSON_ENCODE that comes with PHP to process Chinese content when using json data. Let me introduce to you why such problems occur.
Later I learned from the PHP manual that json_encode and json_decode only support utf-8 encoded characters. GBK characters must be converted if you want to use json, so we can handle it easily
Convert an encoding
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"));
This still sometimes causes problems. Then I found a way to use urlencode() to process all the contents of all arrays before json_encode, then use json_encode() to convert it into a json string, and finally use urldecode() Convert the encoded Chinese back.
/***************************************************** **********
*
* Use a specific function to process all elements in the array
* @param string &$array The string to be processed
* @param string $function The function to be executed
* @return boolean $apply_to_keys_also Whether to also apply to keys
* @access public
*
*************************************************** ***********/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
foreach ($array as $key => $value) {
if (is_array($value)) {
arrayRecursive($array[$key], $function, $apply_to_keys_also);
} else {
$array[$key] = $function($value);
}
/***************************************************** **********
*
* Convert array to JSON string (compatible with Chinese)
* @param array $array The array to be converted
* @return string The converted json string
* @access public
*
*************************************************** ***********/
function JSON($array) {
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
Return urldecode($json);
}http://www.bkjia.com/PHPjc/632125.html
www.bkjia.com
true
http: //www.bkjia.com/PHPjc/632125.htmlTechArticleMany friends may encounter it when using json data using the function JSON_DECODE/JSON_ENCODE that comes with php to process Chinese content. NULL or garbled characters occur. Let me introduce to you why...
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