<?
php
class Response_json_xml{
public static function show(
$code,
$message="",
$data=
array(),
$type){
if(
is_null(
$code)){
return ''
;
}
$data=
array(
'code'=>
$code,
'message'=>
$message,
'data'=>
$data
);
if(
$type=="json"
){
self::json(
$code,
$message,
$data);
die;
}else if(
$type=="array"
){
var_dump(
$data);
die;
}elseif(
$type=="xml"
){
self::xml_encoding(
$code,
$message,
$data);
die;
}else{
//coding....
}
}
/**
*按json方式输出通信
*@param integet $code 状态码
*@param string $message 提示信息
*@param array $data 数据
* return string
*/
public static function json(
$code,
$message,
$data=
array()){
if(
is_null(
$code)){
return ''
;
}
$result=
array(
'code'=>
$code,
'message'=>
$message,
'data'=>
$data
);
echo json_encode(
$result);
die;
}
/**
*按xml方式输出通信
*@param integet $code 状态码
*@param string $message 提示信息
*@param array $data 数据
* return string
*/
public static function xml_encoding(
$code,
$message,
$data=
array()){
if(
is_null(
$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::xml_array(
$result);
$xml.="</root>\n"
;
echo $xml;
}
public static function xml_array(
$result){
$xml=
$attr=""
;
foreach (
$result as $key =>
$value) {
if(
is_numeric(
$key)){
$attr=" id='{
$key}'"
;
$key="item"
;
}
$xml.="<{
$key}{
$attr}>\n"
;
$xml.=
is_array(
$value)?self::xml_array(
$value):
$value;
$xml.="</{
$key}>\n"
;
}
return $xml;
}
}
$data=
array(
'id'=>1,
'name'=>'hgj123',
);
$data1=
array(1,2,3,11,122
);
$type=
isset(
$_GET['type'])?
$_GET['type']:'json'
;
Response_json_xml::show(200,'成功',
$data,
$type);
转载于:https://www.cnblogs.com/hgj123/p/4353945.html
相关资源:JAVA上百实例源码以及开源项目