|
/**
* 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 =" \ 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 );
|