When using data interfaces, we usually need to obtain third-party data interfaces or provide third-party data interfaces. These data formats are usually transmitted in XML or JSON format, this article describes how to use PHP to generate XML format data for third-party calls and how to obtain XML data provided by a third-party. Php generates interface communication data
/*** Generate interface data format */class Response {/*** [show outputs data in a comprehensive manner] * @ param [int] $ code [Status code] * @ param [string] $ message [prompt information] * @ param array $ data [data] * @ param [string] $ type [type] * @ return [string] [return Value] */ public static function show ($ code, $ message, $ data = array (), $ type = '') {if (! Is_numeric ($ code) {return '';} $ result = array ('code' => $ code, 'message' => $ message, 'data' => $ data); if ($ type = 'json') {return self: json ($ code, $ message, $ data );} elseif ($ type = 'xml') {return self: xml ($ code, $ message, $ data );} else {// TODO}/*** [json output data] * @ param [int] $ code [Status code] * @ param [string] $ message [prompt message] * @ param [array] $ data [data] * @ return [string] [return Value] */p Ublic static function json ($ code, $ message, $ data = array () {if (! Is_numeric ($ code) {return '';} $ result = array ('code' => $ code, 'message' => $ message, 'data' => $ data); $ result = json_encode ($ result); return $ result ;} /*** [xml generates data in xml format] * @ param [int] $ code [Status code] * @ param [string] $ message [prompt message] * @ param array $ data [data] * @ return [string] [return Value] */public static function xml ($ code, $ message, $ data = array () {if (! Is_numeric ($ code) {return '';} $ result = array ('code' => $ code, 'message' => $ message, 'data' => $ data); header ("Content-Type: text/xml"); $ xml = "<? Xml version = '1. 0' encoding = 'utf-8'?> \ N "; $ xml. ="
\ N "; $ xml. = self: xmlToEncode ($ data); $ xml. ="
"; Return $ xml;} public static function xmlToEncode ($ data) {$ xml =''; foreach ($ data as $ key => $ value) {if (is_numeric ($ key) {$ attr = "id = '{$ key}'"; $ key = "item" ;}$ xml. = "<{$ key} {$ attr}> \ n"; $ xml. = is_array ($ value )? Self: xmlToEncode ($ value): "{$ value} \ n"; $ xml. ="
\ N ";}return $ xml ;}// test $ grade = array (" score "=> array (70, 95, 70.0, 60," 70 "), "name" => array ("Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "TianQi ")); $ response = new Response (); $ result = $ response: show (200, 'success ', $ grade, 'json'); print_r ($ result );
The above is all the content of this article. I hope you will like it.