: This article mainly introduces the PHP_APP communication interface-encapsulation of communication interfaces. For more information about PHP tutorials, see. Standard format of communication data:
Code Status code (200,400, etc );
Message prompts (logon failure, data return success, etc );
Data returns data;
1. json encapsulation of communication interfaces
Method: json_encode ($ value );
Note: This function can only accept UTF-8 encoded data. if data in other formats is transmitted, the function returns null;
/**
*
Press
Json
Output communication data
*
@ Param
Int $ code
Status Code
*
@ Param
String $ message
Prompt information
*
@ Param
Array $ data
Data
*
@ Return
String
*/
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 ;}}?>
2. encapsulate communication interfaces in xml format
Method: php generates xml data;
First, there are two methods to summarize how php generates xml data:
1. assemble it into an xml string;
2. use the system class (DomDocument, XMLWriter, SimpleXML );
/**
*
Press
Xml
Output communication data
*
@ Param
Int $ code
Status Code
*
@ Param
String $ message
Prompt information
*
@ Param
Array $ data
Data
*
@ Return
Void
*/
Public static function xmlEncode ($ code, $ message = '', $ data = array () {$ r =''; if (! Is_numeric ($ code) $ r = ''; $ result = array ('code' => $ code, 'message' => $ message, 'data' => $ data,); header ("Content-Type: text/xml"); $ xml =" \ N "; $ xml. =" \ N "; $ xml. = self ::
XmlToEncode($ Result); $ xml. =" "; $ R = $ xml; echo $ r;} public static function xmlToEncode ($ data) {$ xml = $ attr = ""; foreach ($ data as $ key => $ value) {if (is_numeric ($ key) {$ attr = "id = '{$ key }'"; $ key = 'ITEM';} $ xml. = "<{$ key} {$ attr}>"; $ xml. = is_array ($ value )? Self ::
XmlToEncode($ Value): $ value; $ xml. =" \ N ";}return $ xml ;}}?>
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.
The above describes the PHP_APP communication interface-the method for encapsulating the communication interface, including the content, hope to be helpful to friends who are interested in the PHP Tutorial.