The following small series for everyone to bring a PHP write app interface and return the JSON data instance (share). Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
The first step: Conn. PHP file to connect to the database and define the interface format, the code is as follows:
<?php Header ("Charset=utf-8"); $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "Test"; $conn = mysql_connect ($servername, $username, $password); if (! $conn) { echo "database connection failed! "; } mysql_select_db ($dbname); Class response{public static function json ($code, $message = "", $data =array ()) { $result =array ( ' code ' = = $code, ' message ' = $message, ' data ' and $data ); Output JSON echo json_encode ($result); Exit; } } ? >
Step two: text.php, which converts the data in the database into a JSON string and outputs:
<?php require_once (' conn.php '); / * * Select data table * */ $sqla = "SELECT * from user"; $result = mysql_query ($sqla, $conn); $dataarr = Array (); while ($row = Mysql_fetch_array ($result)) { $dataarr []= $row; } $id =$_get[' id ']; if ($id ==1) { Response::json (1, ' data returned successfully ', $dataarr); } else if ($id ==2) { Message::json (0, ' failed '); } ? >
Step three: Text.html,ajax loads the JSON data and displays:
<! DOCTYPE html>
This makes it possible to write JSON interfaces using PHP.