The example in this article describes the usage of the function of returning json data in PHP and is shared with everyone for your reference. The specific method is as follows:
json_encode() function usage:
echo json_encode(array('a'=>'bbbb','c'=>'ddddd');
This will generate a standard json format data
<?php //需要执行的SQL语句 //单条 $sql="select id,name from tbl_user where id=1"; //多条数据 //$sql="select id,name from tbl_user"; //调用conn.php文件进行数据库操作 require('Conn.php'); //提示操作成功信息,注意:$result存在于conn.php文件中,被调用出来 if($result) { // $array=mysql_fetch_array($result,MYSQL_ASSOC); /*数据集 $users=array(); $i=0; while($row=mysql_fetch_array($result,MYSQL_ASSOC)){ echo $row['id'].'-----------'.$row['name'].'</br>'; $users[$i]=$row; $i++; } echo json_encode(array('dataList'=>$users)); */ /*单条数据*/ $row=mysql_fetch_row($result,MYSQL_ASSOC); echo json_encode(array('jsonObj'=>$row)); } mysql_free_result($result); //释放结果 mysql_close(); //关闭连接 ?>
The above is the json data generated by the database
Single piece of data: {"jsonObj":{"id":"1","name":"lmw"}}
Multiple pieces of data: {"dataList":[{"id":"1","name":"lmw"},{"id":"2","name":"xxj"},{"id" :"3","name":"xxxj"}]}
In many cases now, we need the program to return a result in Json format, such as:
{ "UserKeyGetResponse": {"RequestName":"e99e6d63e8c712d7699f52978a","api_key_value":"41954dd9b1cb6a95802eab6810"}, "error_response": {"code":"NO_ERROR","msg":"获取系统参数成功"} } 可以将结果写成这样的数组形式: $respon = array('UserKeyGetResponse' => array('RequestName' => $api_request_name, 'api_key_value' => $api_key_value), 'error_response' => array('code' => 'NO_ERROR', 'msg' => '获取系统参数成功'));
The code is as follows:
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--; } g: $error_respon = array('code' => 'ERROR_MSG_MISS', 'msg' => '消息不存在'); echo JSON($array);
The running result is:
{"code":"ERROR_MSG_MISS","msg":"消息不存在"}
The client can parse the result. Of course, the error code must be replaced by a number.
This is much better. What we display is Chinese directly. Of course, there is no problem in displaying the hexadecimal encoding.
I hope this article will be helpful to everyone’s PHP programming design.
You are using jquery to send the ajax request! You can use $.each(msg,function(item,index){
//item represents each object!
//index represents index
});
Refer to the principle of sae's distributed crawling of http pages/
Reference address: e.sae.sina.com.cn/...pstore