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.