php 封装json xml通讯数据方法 php开发APP接口
//php开发APP接口
class Response{
const JSON="json";
public static function show($code,$message,$data=array(),$type=self::JSON){
if(!is_numeric($code)){
return '';
}
$type = isset($_GET['fomat'])? $_GET['fomat'] : self::JSON;
$result=array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
if($type=='json'){
self::json($code,$message,$data);
exit;
}elseif($type=="array"){
var_dump($result);
}elseif($type=='xml'){
self:: xmlEncode($code,$message,$data);
exit;
}else{
echo 'do something';//
}
}
public static function json($code,$message,$data=array()){
if( !is_numeric($code) ){
return '';
}
$result=array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
echo json_encode($result);
exit;
}
public static function xmlEncode(){
header("Content-Type:type/xml");//输出xml格式数据
$xml="<?xml version='1.0' encoding='UTF-8'?>\n";
$xml.="<root>\n";
$xml.="<code>200</code>\n";
$xml.="<message>数据返回成功</message>\n";
$xml.="<data>\n";
$xml.="<id>1</id>\n";
$xml.="<name>kmong</name>\n";
$xml.="</data>\n";
$xml.="</root>\n";
echo $xml;
}
}
//$res=new Response;
//$data=$res->show(200,'成功',array('name'=>'tim','age'=>12));
//var_dump($data);
Response::json(200,"success",$array); 综合封装 xml json格式的通讯数据
$data=array(
id=>1,
name=>'Tom',
'type'=>array(4,5,6),
'test'=>array(1,34,22=>array(1212,'test'));
);
Response::show(200,'success,$data,'array');
访问方法 添加get判断后
locahost//xxx.php?fomate=json