Json data format data is most frequently used for real-time interaction with js and flash. how does php return the json data format? I will analyze the sample code of the. PHP instance as follows :? Phpheader (#39; Con... json data is used most frequently for real-time interaction with js and flash. how does php return the json data format? I will analyze the example below.
The PHP instance code is as follows:
array("a" => "orange", "b" => "banana", "c" => "apple"), "numbers" => array(1, 2, 3, 4, 5, 6), "holes" => array("first", 5 => "second", "third") ); echo json_encode($fruits);?>
There is no problem in english. if it is Chinese, there will be problems. The solution is as follows.
Json only supports UTF-8 encoding. I think the reason is that the front-end Javascript is also UTF-8. the code is as follows:
Iconv ('gb2312', 'utf-8', 'Here is the Chinese title'), 'body' => 'abcd... '); echo json_encode ($ array);?>
// The result is as follows:
{"Title": "u8fd9u91ccu662fu4e2du6587u6807u9898", "body": "abcd ..."}
Use js to analyze this function. the code is as follows:
$(function(){ $('#send').click(function() { $.getJSON('json.php', function(data) { $('#resText').emptyempty(); var html = ''; $.each( data , function(commentIndex, comment) { html += '' + comment['username'] + ':
' + comment['content'] + '
'; }) $('#resText').html(html); }) }) })
Note that when your php output js format, we must be the header ('content-type: text/json'); such header information is sent, A complete program for parsing Chinese garbled characters is added. The code is as follows:
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_e Ncode ($ array); return urldecode ($ json);} $ array = array ('name' => 'xia', 'age' => 20 ); echo JSON ($ array);?>
Address:
Reprinted at will, but please attach the article address :-)