PHP以json或xml格式返回请求数据的方法
前端之家收集整理的这篇文章主要介绍了
PHP以json或xml格式返回请求数据的方法,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_0@无论是网页还是移动端,都需要向服务器请求数据,那么作为PHP服务端,如何返回标准的数据呢?
@H_
502_0@现在主流的数据格式无非就是json和xml,下面我们来看看如何用
PHP来封装一个返回这两种格式数据的类
@H_
502_0@
我们先定义一个响应类
<div class="jb51code">
<pre class="brush:xhtml;">
class response{
}
@H_
502_0@
1、以json格式返回数据
@H_
502_0@json格式返回数据比较简单,直接将我们
后台获取到的数据,以标准json格式返回给请求端即可
$code,"message"=>$message,"data"=>$data
);
echo json_encode($result);
}
@H_
502_0@
2、以xml格式返回数据
@H_
502_0@这种方式需要遍历data里面的数据,如果数据里有数组还要递归遍历。还有一种特殊情况,当数组的下标为数字时,xml格式会报错,需要将xml中数字
标签替换
$code,"data"=>$data
);
header("Content-Type:text/xml");
$xml="";
$xml.="";
$xml.=self::xmlToEncode($result);
$xml.="";
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}>";
}
return $xml;
}
}
@H_
502_0@
3、将两种格式封装为一个方法,完整代码如下:
$code,"data"=>$data
);
if($type=='json'){
self::json($code,$data);
exit;
}elseif($type=='xml'){
self::xmlEncode($code,$data);
exit;
}else{
//后续
添加其他格式的数据
}
}
//按json格式返回数据
public static function json($code,"data"=>$data
);
echo json_encode($result);
}
//按xml格式返回数据
public static function xmlEncode($code,"data"=>$data
);
header("Content-Type:text/xml");
$xml="";
$xml.="
";
$xml.=self::xmlToEncode($result);
$xml.="";
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}>";
}
return $xml;
}
}
$data=array(1,231,123465,array(9,8,'pan'));
response::show(200,'success',$data,'json');
@H_
502_0@这样我们
调用show
方法时,需要传递四个参数,第四个参数为想要返回的数据格式,默认为json格式,
效果如下:
@H_
502_0@

@H_
502_0@我们再
调用一次show
方法,以xml格式返回数据:
@H_
502_0@
@H_
502_0@

@H_
502_0@这样我们就完成了对这两种数据格式的封装,可以随意返回这两种格式的数据了
@H_
502_0@以上这篇
PHP以json或xml格式返回请求数据的
方法就是小编
分享给大家的全部
内容了,希望能给大家一个参考,也希望大家多多
支持编程之家。