通信数据的标准格式:
code状态码(200,400等);
message提示信息(登录失败,数据返回成功等);
data返回数据;
1、json 方式封装通信接口
方法:json_encode($value);
注:该函数只能接受utf-8编码的数据;如果传递其他格式的数据该函数会返回null;
classResponse {/***按json方式输出通信数据*@paramint $code状态码*@paramstring $message提示信息*@paramarray $data数据*@returnstring*/public static functionjson($code,$message='',$data=array()) {if(!is_numeric($code))return'';$result=array('code'=>$code,'message'=>$message,'data'=>$data,);echojson_encode($result);exit;} }?>
2、xml的方式封装通信接口
方法:php生成xml数据;
首先php如何生成xml数据,总结有两种方法:
1.组装成xml字符串;
2.使用系统类(DomDocument、XMLWriter、SimpleXML);
classResponse {/***按xml方式输出通信数据*@paramint $code状态码*@paramstring $message提示信息*@paramarray $data数据*@returnvoid*/public static functionxmlEncode($code,$message='',$data=array()) {$r='';if(!is_numeric($code))$r='';$result=array('code'=>$code,'message'=>$message,'data'=>$data,);header("Content-Type:text/xml");$xml="
\n";$xml.="
\n";$xml.=self::xmlToEncode($result);$xml.="";$r=$xml;echo$r;}public static functionxmlToEncode($data) {$xml=$attr="";foreach($dataas$key=>$value) {if(is_numeric($key)) {$attr="id='{$key}'";$key='item';}$xml.="{$key} {$attr}>";$xml.= is_array($value)?self::xmlToEncode($value):$value;$xml.="{$key}>\n";}return$xml;} }?>
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了PHP_APP通信接口—封装通信接口的方法,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。