Php encapsulation json communication interface details and examples, php encapsulation json details

Source: Internet
Author: User

Php encapsulation json communication interface details and examples, php encapsulation json details

JSON Data creation in php:

<? Php // create a character array $ arr = array ('id' => 1, 'name' => 'David '); echo json_encode ($ arr ); // is this key function for creating JSON?>

Implementation result

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

Note: json_encode ($ value); this function can only receive UTF-8 encoded data. If data in other formats is transmitted to this function, null is returned;

Data method for encapsulating communication interfaces

1. standard communication data format:
0111 code status code (200,400). For example, if the logon succeeds at 200, the logon fails at 400.
Message (Incorrect email format, 200 indicates successful logon)
Data returned data

Instance:

Demo. php

<? Php class Response {/*** output Communication data in json format * @ param integer $ code status code * @ param string $ message prompt message * @ param array $ data * return string return Value: json * // static method, construct 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"> 

The main file test. PHP calls the method of the above class to create json data

<? Php // run the demo. php contains this file once require_once ('. /demo. php '); $ arr = array ('id' => 1, 'name' => 'David'); // call the json method Response of the Resonpse class :: json (200, 'Data returned successfully', $ arr);?>

Result of running test. php:

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

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

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.