php生成json或者xml数据

<?php
/**
* Created by PhpStorm.
* User: yihuaiyuan
* Date: 16/10/9
* Time: 上午9:47
*/
php生成json或者xml数据
vim Response.php
<?php
class Response{
/**
*按json方式输出通信数据
*@param integert $code 状态码
*@param string $message 提示信息
*@param array $data 数据
*return string
*/
public static function json($code,$message='',$data=array()){

if(!is_numeric($code)){
return "";
}
$result = array(
'code' => $code,
'message' => $message,
'data' => $data
);

return json_encode($result);

}

/**
*按xml方式输出通信数据
*@param integert $code 状态码
*@param string $message 提示信息
*@param array $data 数据
*return string
*/
public static function xmlEncode($code,$message='',$data){
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'?> ";
$xml.="<root> ";
$xml.=self::xmlToEncode($result);
$xml.="</root>";

return $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}> ";
}
return $xml;
}

/**
*按综合方式输出通信数据
*@param integert $code 状态码
*@param string $message 提示信息
*@param array $data 数据
*@param string $type 数据类型
*return string
*/
public static function show($code,$message='',$data=array(),$type='json'){
if(!is_numeric($code)){
return "";
}
$type=isset($_GET['format'])?$_GET['format']:$type;
$result=array(
'code' => $code,
'message' => $message,
'data' => $data
);

if($type == 'json'){
$json = self::json($code,$message,$data);
return $json;
}elseif($type == 'array'){
return $result;
}elseif($type == 'xml'){
$xml = self::xmlEncode($code,$message,$data);
return $xml;
}else{
//TODO
}
}
}
?>

vim test.php
<?php
/*直接调用*/
require_once('./Response.php');
$arr = array(
'id' =>1,
'name' => 'xiaoming'
);
$xml = Response::show(200,'数据返回成功',$arr);
echo $xml;
?>
原文地址:https://www.cnblogs.com/eis13/p/5941122.html