App 接口实现
class Response {
const JSON = “json”;
/*
按综合方式输出
@param integer $code 状态码
@param string $message 提示信息
@param string $type 输出格式
@param array $data 数据
*/
public static function show($code,$message='',$data=array(),$type=self::JSON) {
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::json($code,$message,$data);
exit;
} elseif($type=='array') {
var_dump($result);
exit;
} elseif($type=='xml') {
self::xmlEncode($code,$message,$data);
exit;
} else {
//TODO
}
}
/*public static function xml() {
header('Content-Type:text/xml');//请求 header文件格式 xml
$xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xml .= "<root>\n";
$xml .= "<code>200</code>\n";
$xml .= "<message>数据返回成功</message>\n";
$xml .= "<data>swan</data>\n";
$xml .= "</root>";
echo $xml;
}*/
/*
按json方式输出
@param integer
code状态码@paramstring
message 提示信息
@param array
data数据∗/publicstaticfunctionjson(
code,
message,
data) {
if(!is_numeric($code)) {
return ”;
}
$array = array(
'code' => $code,
'message' => $message,
'data' => $data
);
echo json_encode($array);
exit;
}
/*
按xml方式输出
@param integer $code 状态码
@param string $message 提示信息
@param array $data 数据
*/
public static function xmlEncode($code,$message,$data=array()){
if(!is_numeric($code)) {
return '';
}
$result = array(
'code' =>$code,
'message' =>$message,
'data' =>$data
);
header("Content-Type:text/xml");
$xml = "<?xml version='1.0' encoding='UTF-8' ?>\n";
$xml .= "<root>\n";
$xml .= self::xmlToEncode($result);
$xml .= "</root>";
echo $xml;
}
public static function xmlToEncode($data) {
$xml = $attr = "";
foreach($data as $key => $value) {
if(is_numeric($key)) {
$attr = "id = '{$key}'";
$key = "item";
}
$xml .= "<{$key} {$attr}>";
$xml .= is_array($value)?self::xmlToEncode($value):$value;
$xml .= "</{$key}>\n";
}
return $xml;
}
}
$data = array(
‘title’ =>1,
‘movie’ =>’sun’,
‘type’ => array(1,2,4),//<0>1<1>2<2>4
‘tree’ => array(2,34,54 =>array(4,5,6))
);