PHP對接APP的介面類,可返回json資料,xml資料
阿新 • • 發佈:2018-12-05
<?php /* * APP資料處理類 * 作 者:永樂開發 * 日 期:2017.7.31 * 郵 箱:[email protected] * 博 客:http://www.isu5.cn http://it.alipea.com */ class Response{ /** * 綜合方法 預設json方法呼叫 * @param integer $code 狀態碼 * @param string $msg 提示資訊 * @param string $data 資料 * return string * */ public static function show($code,$msg,$data=[],$type=''){ if (!is_numeric($code)) { return ''; } $result = array( 'code' => $code, 'msg' => $msg, 'data' => $data ); $type = $_GET['format'] ? $_GET['format'] : ''; if ($type=='json') { //json形式 self::returnJson($code,$msg,$result); exit; }elseif ($type=='array') { //陣列形式 var_dump($result); }elseif ($type=='xml') { self::xmlEncode($code,$msg,$result); exit; }else{ //TODO } } /** * 按json資料傳輸 * @param integer $code 狀態碼 * @param string $msg 提示資訊 * @param string $data 資料 * return string * */ public static function returnJson($code,$msg,$data=[],$type='json'){ if (!is_numeric($code)) { return ''; } $result = array( 'code' => $code, 'msg' => $msg, 'data' => $data ); echo json_encode($result); exit; } /** * 按xml資料傳輸 * @param integer $code 狀態碼 * @param string $msg 提示資訊 * @param string $data 資料 * return string * */ public static function xmlEncode($code,$msg,$data=[]){ if (!is_numeric($code)) { return ''; } $result = array( 'code' => $code, 'msg' => $msg, '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>"; echo $xml; } public static function xmlToEncode($data){ $xml = $attr = ""; foreach ($data as $key => $value) { //如果key值為數字 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; } }
呼叫方法:
Response::show(200,'提示資訊',$data);
訪問地址:
http://localhost/index.php?format=json 返回json資料
http://localhost/index.php?format=xml 返回xml資料