PHP implements class sharing that returns JSON and XML, and php returns jsonxml
The code is very concise, and the function is also very simple and practical. I won’t go into too much nonsense here and just give you the code:
Copy code The code is as follows:
class Reponse{
//private $result = array('code'=null,'message'=null,'data'=>null);
/**
* @desc returns 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 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 .= "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 .= "{$key}>n";
}
return $xml;
}
}
$data = array(
'id'=>1,
'age'=>20,
'username'=>'tim',
'others'=>array(1,2,3),
);
Response::xml(200,'success',$data);
Response::json(200,'success',$data);
Friends can use it directly, the usage method is at the bottom of the code:)
http://www.bkjia.com/PHPjc/949457.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/949457.htmlTechArticlePHP implements class sharing that returns JSON and XML. PHP returns jsonxml. The code is very concise and the function is simple and practical. Here Without further ado, here is the code: Copy the code as follows: ph...