PHP implements class sharing that returns JSON and XML, and php returns jsonxml. PHP shares classes that return JSON and XML. the jsonxml code returned by php is concise, and the function is very simple and practical. there is not much nonsense here. the code is directly presented: Copy the code as follows: PHP implements class sharing that returns JSON and XML, and php returns jsonxml
The code is concise and the function is very simple and practical. there is not much nonsense here, and the code is provided directly:
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 :)
The pipeline code is very concise, and the function is very simple and practical. there is not much nonsense here, and the code is provided directly: the code is as follows: ph...