PHP实现返回JSON和XML的类分享
程序员文章站
2022-11-01 10:12:14
代码很简洁,功能也很简单实用,这里就不多废话了,直接奉上代码:
复制代码 代码如下:
<?php
class reponse{
//private $result = array('code'=null,'message'=null,'data'=>null);
/**
* @desc 返回json格式
* @param int $code
* @param string $message
* @param array $data
* return string
*/
public static function json($code,$message = null,$data = array()){
if(!is_numeric($code)){
return false;
}
$result = array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
return json_encode($result);
exit;
}
/**
* @desc 返回xml格式数据
* @parma int $code 状态码
* @param string $message 提示
* @param array $data 数据
* return string
*/
public static function xml($code,$message = '',$data = array()){
if(!is_numeric($code)){
return false;
}
$result = array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
$xml = '';
$xml .= "<?xml version='1.0' encoding='utf-8'?>\n";
$xml .= "<root>\n";
$xml .= self::xmlencode($result);
$xml .= "</root>";
header("content-type:text/xml");
echo $xml;
}
public static function xmlencode($result){
$xml = $attr ='';
foreach($result as $key=>$val){
if(is_numeric($key)){
$attr = "id='{$key}'";
$key = "item{$key}";
}
$xml .= "<{$key} {$attr}>";
$xml .= is_array($val) ? self::xmlencode($val) : $val;
$xml .= "</{$key}>\n";
}
return $xml;
}
}
$data = array(
'id'=>1,
'age'=>20,
'username'=>'tim',
'others'=>array(1,2,3),
);
reponse::xml(200,'success',$data);
reponse::json(200,'success',$data);
代码很简洁,功能也很简单实用,这里就不多废话了,直接奉上代码:
复制代码 代码如下:
<?php
class reponse{
//private $result = array('code'=null,'message'=null,'data'=>null);
/**
* @desc 返回json格式
* @param int $code
* @param string $message
* @param array $data
* return string
*/
public static function json($code,$message = null,$data = array()){
if(!is_numeric($code)){
return false;
}
$result = array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
return json_encode($result);
exit;
}
/**
* @desc 返回xml格式数据
* @parma int $code 状态码
* @param string $message 提示
* @param array $data 数据
* return string
*/
public static function xml($code,$message = '',$data = array()){
if(!is_numeric($code)){
return false;
}
$result = array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
$xml = '';
$xml .= "<?xml version='1.0' encoding='utf-8'?>\n";
$xml .= "<root>\n";
$xml .= self::xmlencode($result);
$xml .= "</root>";
header("content-type:text/xml");
echo $xml;
}
public static function xmlencode($result){
$xml = $attr ='';
foreach($result as $key=>$val){
if(is_numeric($key)){
$attr = "id='{$key}'";
$key = "item{$key}";
}
$xml .= "<{$key} {$attr}>";
$xml .= is_array($val) ? self::xmlencode($val) : $val;
$xml .= "</{$key}>\n";
}
return $xml;
}
}
$data = array(
'id'=>1,
'age'=>20,
'username'=>'tim',
'others'=>array(1,2,3),
);
reponse::xml(200,'success',$data);
reponse::json(200,'success',$data);
小伙伴们可以直接拿去使用,使用方法在代码的最下方:)