PHP开发APP接口 记录

来源:互联网 发布:java读取gz文件 编辑:程序博客网 时间:2024/05/22 04:37
用于 把数据返给APP接口使用 ,返回 方式有 xml,json,array

class Response {/*** 综合方式输出数据* @param integer $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 '';}$result = array('code' => $code,'message' => $message,'data' => $data,);if($type == 'json') {echo self::json($code, $message, $data);exit;} elseif($type == 'array') {var_dump($result);} elseif($type == 'xml') {echo self::xml($code, $message, $data);exit;} else {//没有类型return false;}}//将数据转化为jsonpublic static function json($code, $message = '', $data = array()) {if(!is_numeric($code)) {return '';}$result = array('code' => $code,'message' => $message,'data' => $data);    return json_encode($result);}//将数据转化为xmlpublic static function xml($code, $message, $data = array()) {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'?>\n";$xml .= "<root>\n";$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}>\n";}return $xml;}}


实例: 

<?phpinclude_once('response.php');$data = ['name'=>'D','age'=>'18'];//url后面加个 type 参数,用get获取,方便让app工程师得到需要的数据格式$type = empty($_GET['type'])?'json':$_GET['type'];Response::show('200','success',$data,$type);