Home >Backend Development >PHP Tutorial >The php json_encode() function returns the json data instance code, json_encodejson_PHP tutorial
json_encode() function usage.
echo json_encode(array('a'=>'bbbb','c'=>'ddddd');
This will generate a standard json format data
The code is as follows
<?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:
The code is as follows
The result is:
{"code":"ERROR_MSG_MISS","msg":"Message does not exist"}
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.
Use the json_decode function to decrypt the data. . The function for PHP to apply JSON is: json_encode($PHPcode);
The function for PHP to parse JSON is: json_decode($JSONcode); so there are many forms of JSON, and different forms have different forms after being interpreted by PHP. . //Form 1: It is completely in the form of an object. This form of data is also called a related array in Javascript. Different from ordinary arrays, it can be accessed through a string as an index (use "[]" or "." to represent the level) $json='{"item1":{"item11":{"n":"chenling", "m":"llll"},"sex":"male","age":"25 "},"item2": {"item21":"ling","sex":"女","age":"24"}}'; $J=json_decode($json); print_r($J); Take a look at this article about php operating json data from the PHP Beginner's Guide: www.phpnewer.com/index.php/Cjwt/detail/id/147
Dear, you didn’t execute it in the environment at all. You need to compile it with php+apache