接口文件response.php
<?php
class Response{
//默认是json格式
const JSON='json';
public static function show($code,$message='',$data=array(),$type){
if(!is_numeric($code)){
return '';
}
//为前端开发人员提供接口
$type=isset($_GET['format'])?$_GET['format']:self::JSON;
$result=array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
if($type=='json'){
self::jsonEncode($code,$message,$data);
exit;
}elseif($type=='array'){
//调试
var_dump($result);
}elseif($type=="xml"){
self::xmlEncode($code,$message,$data);
exit;
}else{
//html
}
}
public static function jsonEncode($code,$message='',$data=array()){
if(!is_numeric($code)){
return '';
}
//把要返回给前端的数据组合
$result=array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
//array => json
echo json_encode($result);
exit;
}
public static function xmlEncode($code,$message,$data){
if(!is_numeric($code)){
return '';
}
//告诉浏览器该格式为xml
header("Content-Type:text/xml");
$result=array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
$xml='';
//xml声明是必要的
$xml.="<?xml version='1.0' encoding='UTF-8'?>";
//根节点是必要的
$xml.="<root>";
$xml.=self::xmlToEncoding($result);
$xml.="</root>";
echo $xml;
}
public static function xmlToEncoding($result){
foreach($result as $key=>$val){
//处理根节点为数字 xml是不允许的 所以使用id号来区别
if(is_numeric($key)){
$attr="id='{$key}'";
$key="item";
}
$xml.="<{$key} {$attr}>";
$attr='';
$xml.=is_array($val)?self::xmlToEncoding($val):$val;
$xml.="</{$key}>";
}
return $xml;
}
}
?>
test.php
<?php
require_once('./Response.php');
$code='200';
$message="成功";
$data=array(
'name'=>'小红',
'age'=>23,
'type'=>array(1,2,3)
);
<?php
require_once('./Response.php');
$code=200;
$message="成功";
$data=array(
'name'=>'小红',
'age'=>23,
'type'=>array(1,2,3)
);
// Process::jsonEncode($code,$message,$data);
// Process::xmlEncode($code,$message,$data);
Response::show($code,$message,$data,'xml');
网友评论