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!