/** * 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-based data output] * @ Param [int] $ code [Status code] * @ Param [string] $ message [prompt information] * @ Param [array] $ data [data] * @ Return [string] [return Value] */ Public 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 information] * @ 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. = "<root> \ n "; $ Xml. = self: xmlToEncode ($ data ); $ Xml. = "</root> "; 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. = "</{$ key}> \ 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 ); |