The json_encode () built-in function (php> 5.2) in php can be used to transmit and use data in php with other languages.
This function converts a value to a json data storage format.
[Php]
<? Php
$ Arr = array
(
'Name' => 'chia ',
'Age' => 20
);
$ Jsonencode = json_encode ($ arr );
Echo $ jsonencode;
?>
The program running result is as follows:
[Php]
{"Name": null, "Age": 20}
In the json_encode function, Chinese characters are encoded as null. After Google, it is very simple. To work closely with the front-end, Json only supports UTF-8 encoding. I think the front-end Javascript is also the reason for UTF-8 encoding.
[Php]
<? Php
$ Array = array
(
'Title' => iconv ('gb2312', 'utf-8', 'Here is the Chinese title '),
'Body' => 'abcd ...'
);
Echo json_encode ($ array );
?>
The running result of this program is:
[Php]
{"Title": "\ u8fd9 \ u91cc \ u662f \ u4e2d \ u6587 \ u6807 \ u9898", "body": "abcd ..."}
All Chinese characters in the array are lost after json_encode or \ u2353 is displayed.
The solution is to use the urlencode () function to process the following. Before json_encode, urlencode () is used to process all the content in the array, and json_encode () is used to convert the content into a json string, finally, use urldecode () to convert the Encoded chinese characters back.
[Php]
<? Php
/*************************************** ***********************
* Www.2cto.com
* 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 it is also applied to the key
* @ Access public
*
**************************************** *********************/
Function arrayRecursive (& $ array, $ function, $ apply_to_keys_also = false)
{
Static $ recursive_counter = 0;
If (++ $ recursive_counter> 1000 ){
Die ('possible deep recursion attack ');
}
Foreach ($ array as $ key => $ value ){
If (is_array ($ value )){
ArrayRecursive ($ array [$ key], $ function, $ apply_to_keys_also );
} Else {
$ Array [$ key] = $ function ($ value );
}
If ($ apply_to_keys_also & is_string ($ key )){
$ New_key = $ function ($ key );
If ($ new_key! = $ Key ){
$ Array [$ new_key] = $ array [$ key];
Unset ($ array [$ key]);
}
}
}
$ Recursive_counter --;
}
/*************************************** ***********************
*
* Convert an array to a JSON string (compatible with Chinese characters)
* @ 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 );
}
$ Array = array
(
'Name' => 'chia ',
'Age' => 20
);
Echo JSON ($ array );
?>
The operation is successful. The result is as follows:
[Php] view plaincopy
{"Name": "Sia", "Age": "20 "}
Author: wolinxuebin