PHP開發APP介面 記錄
阿新 • • 發佈:2018-12-26
用於 把資料返給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; } } //將資料轉化為json public static function json($code, $message = '', $data = array()) { if(!is_numeric($code)) { return ''; } $result = array( 'code' => $code, 'message' => $message, 'data' => $data ); return json_encode($result); } //將資料轉化為xml public 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; } }
例項:
<?php
include_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);