PHP Encapsulation JSON Communication interface method

Source: Internet
Author: User
This article mainly introduces the PHP encapsulation JSON communication interface details and examples of relevant information, the need for friends can refer to the following

PHP creates JSON data in a detailed detail:

<?php  //Create an array of characters $arr =array (   ' id ' =>1,   ' name ' = ' David ');   echo Json_encode ($arr);//This is the key function to create JSON?>

Achieve results

{"id": 1, "name": "David"}

Note: Json_encode ($value); This function can only receive UTF-8 encoded data. Other format data is passed to the function to return null;

Data methods for encapsulating communication interfaces

1. Communication Data Format standard:
0111 Code Status Code (200,400) such as: Logon success 200, unsuccessful 400
Message hint message (message format is incorrect, 200 for login success)
Data returned

Instance:

demo.php

<?php   class response{/** * Output Communication data as JSON * @param integer $code Status code * @param string $message message * @param array $data Data *return string return value is JSON///static method, constructs JSON data public static function JSON ($code, $message = ", $data =array ()) {    if (!is_ Numeric ($code)) {    return ';    }   $result =array (   ' Code ' = $code,   ' message ' = $message,   ' data ' = $data    ); Echo Json_encode ($ result); Exit;   } }?>

</pre><pre name= "code" class= "PHP" >

Test. PHP main file, call the method of the above class, create JSON data

<?php  //demo.php included in this file once Require_once ('./demo.php ');  $arr =array (' id ' =>1, ' name ' = ' David '); Call the JSON method of the Resonpse class Response::json (200, ' data return succeeded ', $arr);?>

Run test.php results:

{"Code": $, "message": "\u6570\u636e\u8fd4\u56de\u6210\u529f", "data": {"id": 1, "name": "David"}}

The above is the whole content of this article, I hope that everyone's study has helped.


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.