视屏:https://www.imooc.com/video/2808
新建 format.php文件
<?php
/**
* @Author: Marte
* @Date: 2018-10-08 20:02:51
* @Last Modified by: Marte
* @Last Modified time: 2018-10-08 22:37:44
*/
class Format{
/**
* 以合并json以及xml格式进行输出
* @param [int] [code] [状态码]
* @param [string] [string] [返回信息]
* @param [array] [type] [返回类型]
* @param [string] [data] [操作数据]
*/
const JSON='json';
public static function Show($code,$massage='',$data=array(),$type=self::JSON){
if(!is_numeric($code)){
return '';
}
$type=isset($_GET['format'])?$_GET['format']:self::JSON;
$result=array(
'code' =>$code,
'massage'=>$massage,
'data'=>$data,
);
if($type=='json'){
self::ToJson($code,$massage,$data);
exit;
}elseif($type=='array'){
var_dump($data);
}elseif($type=='xml'){
self::ToXml($code,$massage,$data);
exit;
}else{
//TODO
}
}
/**
* 以json格式进行数据的返回
* @param [int] [code] [状态码]
* @param [string] [string] [返回信息]
* @param [array] [type] [返回类型]
*
*/
public static function ToJson($code,$massage='',$data=array()){
if(!is_numeric($code)){
return '';
}
$result= array(
'code' =>$code,
'massage'=>$massage,
'data'=>$data,
);
echo json_encode($result);
exit;
}
/**
* 以xml格式进行数据的返回
* @param [int] [code] [状态码]
* @param [string] [string] [返回信息]
* @param [array] [type] [返回类型]
*
*/
public function ToXml($code,$massage='',$data=array()){
if (!is_numeric($code)) {
return '';
}
$result=array(
'code'=>$code,
'massage'=>$massage,
'type'=>$data,
);
header("Content type:text/xml");
$xml="<?xml version='1.0' encoding='UTF-8'?>";
$xml.="<root> \n";
$xml.=self::ToGetXml($result);
$xml.="</root>";
echo $xml;
exit;
}
public static function ToGetXml($date){
$xml='';
$attr='';
foreach ($date as $key => $value) {
if(is_numeric($key)){
$attr="id='{$key}'";
$key='item';
}
$xml.="<{$key} {$attr}>";
$xml.=is_array($value)?self::ToGetXml($value):$value;
$xml.="</{$key}>";
}
return $xml;
}
}
测试文件
test.php
<?php
/**
* @Author: Marte
* @Date: 2018-10-08 20:37:57
* @Last Modified by: Marte
* @Last Modified time: 2018-10-08 22:33:56
*/
// 测试json返回数据
require_once("./Format.php");
$data=array(
'id'=>100,
'age'=>30,
'type'=>'sex',
'test'=>array(1,2,3,4),
);
$Format=new Format();
//$Format->ToJson(200,'success',$data);
//$Format->ToXml(200,'success',$data);
$Format->Show(200,'success',$data);