json 数据格式数据用得最多的是与js,flash实时交互用的,那么php怎么返回json数据格式呢,下面我来分析一下实例.
PHP实例代码如下:
1 2 3 4 5 6 7 8 9 | <!--?php header('Content-type: text/json'); $fruits = array ( "fruits" =--> 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 ); ?> |
上面是英文是没有问题,如果是中文就会有问题,解决办法如下.
Json 只支持 utf-8 编码,我认为是前端的 Javascript 也是 utf-8 的原因,代码如下:
1 2 3 4 5 6 7 | <!--?php $array = array ( 'title' =--> iconv( 'gb2312' , 'utf-8' , '这里是中文标题' ) , 'body' => 'abcd...' ); echo json_encode( $array ); ?> |
//结果如下:
{"title":"u8fd9u91ccu662fu4e2du6587u6807u9898","body":"abcd..."}
利用js来分析这个函数,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 | $( function (){ $( '#send' ).click( function () { $.getJSON( 'json.php' , function (data) { $( '#resText' ).emptyempty(); var html = '' ; $.each( data , function (commentIndex, comment) { html += '<div class="comment"><h6>' + comment[ 'username' ] + ':</h6><p class="para">' + comment[ 'content' ] + '</p></div>' ; }) $( '#resText' ).html(html); }) }) }) |
注意在你的php输出js格式时我们必须是header('Content-type: text/json');这样的头部信息发送,后面加一个完整的可解析中文乱码的问题程序,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | <!--?php /************************************************************** * * 使用特定function对数组中所有元素做处理 * @param string &$array 要处理的字符串 * @param string $function 要执行的函数 * @return boolean $apply_to_keys_also 是否也应用到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 --; } /************************************************************** * * 将数组转换为JSON字符串(兼容中文) * @param array $array 要转换的数组 * @return string 转换得到的json字符串 * @access public * *************************************************************/ function JSON( $array ) { arrayRecursive( $array , 'urlencode' , true); $json = json_encode( $array ); return urldecode( $json ); } $array = array ( 'Name' => '希亚' , 'Age' => 20 ); echo JSON( $array ); ?> |