手机版

PHP以数据或可扩展标记语言格式返回请求数据的方法

时间:2021-08-31 来源:互联网 编辑:宝哥软件园 浏览:

无论是网页还是移动端,都需要向服务器请求数据,那么作为服务器端编程语言(专业超文本预处理器的缩写)服务端,如何返回标准的数据呢?

现在主流的数据格式无非就是数据和xml,下面我们来看看如何用服务器端编程语言(专业超文本预处理器的缩写)来封装一个返回这两种格式数据的类

我们先定义一个响应类

班级反应{ 1 },以数据格式返回数据

数据格式返回数据比较简单,直接将我们后台获取到的数据,以标准数据格式返回给请求端即可

//按数据格式返回数据公共静态函数json($code,$message,$data=array()){ if(!is _ numeric($ code)){ return " ";} $result=array('code'=$code,' message'=$message,' data '=$ data);echo JSON _ encode($ result);}2、以可扩展标记语言格式返回数据

这种方式需要遍历数据里面的数据,如果数据里有数组还要递归遍历。还有一种特殊情况,当数组的下标为数字时,xml格式会报错,需要将可扩展标记语言中数字标签替换

//按可扩展标记语言格式返回数据公共静态函数xmlEncode($code,$message,$data=array()){ if(!is _ numeric($ code)){ return " ";} $result=array('code'=$code,' message'=$message,' data '=$ data);标题(“内容类型:文本/XML”);$xml='?可扩展标记语言版本='1.0 '编码='UTF-8 '?$xml .=' root$xml .=self : xmlteoncode($ result);$xml .='/root ';echo $ xml}公共静态函数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 : xmlteoncode($ value): $ value;$xml .='/{ $ key } ';}返回$ xml}}3、将两种格式封装为一个方法,完整代码如下:

类响应{公共静态函数show($code,$message,$data=array(),$type='json'){ /** *按综合方式输出通信数据*@param整数$代码状态码*@param字符串$消息提示信息*@param数组$数据数据*@param字符串$类型数据类型*返回字符串*/if(!is _ numeric($ code)){ return " ";} $result=array('code'=$code,' message'=$message,' data '=$ data);if($ type==' JSON '){ self : JSON($ code,$message,$ data);退出;} else if($ type==' XML '){ self : xmlencode($ code,$message,$ data);退出;}else{ //后续添加其他格式的数据} } //按数据格式返回数据公共静态函数json($code,$message,$data=array()){ if(!is _ numeric($ code)){ return " ";} $result=array('code'=$code,' message'=$message,' data '=$ data);echo JSON _ encode($ result);} //按可扩展标记语言格式返回数据公共静态函数xmlEncode($code,$message,$data=array()){ if(!is _ numeric($ code)){ return " ";} $result=array('code'=$code,' message'=$message,' data '=$ data);标题(“内容类型:文本/XML”);$xml='?可扩展标记语言版本='1.0 '编码='UTF-8 '?$xml .=' root$xml .=self : xmlteoncode($ result);$xml .='/root ';echo $ xml}公共静态函数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 : xmlteoncode($ value): $ value;$xml .='/{ $ key } ';}返回$ xml}}$data=array(1,231,123465,array(9,8,' pan ');response:show(200,‘success’,$data,‘JSON’);这样我们调用显示方法时,需要传递四个参数,第四个参数为想要返回的数据格式,默认为数据格式,效果如下:

我们再调用一次显示方法,以可扩展标记语言格式返回数据:

response:show(200,‘success’,$data,‘XML’);效果如下:

这样我们就完成了对这两种数据格式的封装,可以随意返回这两种格式的数据了

以上这篇服务器端编程语言(专业超文本预处理器的缩写)以数据或可扩展标记语言格式返回请求数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

版权声明:PHP以数据或可扩展标记语言格式返回请求数据的方法是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。