This article mainly shares with you a class that uses PHP to return JSON and XML. it is very practical. I hope you will enjoy the concise code and the simple and practical functions. there is no nonsense here, directly provide the code:
The code is as follows:
<? Php
Class Reponse {
// Private $ result = array ('code' = null, 'message' = null, 'data' => null );
/**
* @ Desc return JSON format
* @ Param int $ code
* @ Param string $ message
* @ Param array $ data
* Return string
*/
Public static function json ($ code, $ message = null, $ data = array ()){
If (! Is_numeric ($ code )){
Return false;
}
$ Result = array (
'Code' => $ code,
'Message' => $ message,
'Data' => $ data
);
Return json_encode ($ result );
Exit;
}
/**
* @ Desc return xml format data
* @ Parma int $ code Status code
* @ Param string $ message prompt
* @ Param array $ data
* Return string
*/
Public static function xml ($ code, $ message = '', $ data = array ()){
If (! Is_numeric ($ code )){
Return false;
}
$ Result = array (
'Code' => $ code,
'Message' => $ message,
'Data' => $ data
);
$ Xml = '';
$ Xml. = "<? Xml version = '1. 0' encoding = 'utf-8'?> \ N ";
$ Xml. =" \ N ";
$ Xml. = self: xmlEncode ($ result );
$ Xml. =" ";
Header ("Content-Type: text/xml ");
Echo $ xml;
}
Public static function xmlEncode ($ result ){
$ Xml = $ attr = '';
Foreach ($ result as $ key => $ val ){
If (is_numeric ($ key )){
$ Attr = "id = '{$ key }'";
$ Key = "item {$ key }";
}
$ Xml. = "<{$ key} {$ attr}> ";
$ Xml. = is_array ($ val )? Self: xmlEncode ($ val): $ val;
$ Xml. =" \ N ";
}
Return $ xml;
}
}
$ Data = array (
'Id' => 1,
'Age' => 20,
'Username' => 'Tim ',
'Others '=> array (1, 2, 3 ),
);
Reponse: xml (200, 'success', $ data );
Reponse: json (200, 'success', $ data );
You can use the code directly at the bottom of the code :)