Share about PHP Write app interface and return JSON data instance

Source: Internet
Author: User
Tags php write
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.