這篇文章主要介紹了關於PHP以json或xml格式返回請求資料的方法,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
無論是網頁還是移動端,都需要向伺服器請求資料,那麼作為php服務端,如何返回標準的資料呢?
現在主流的資料格式無非就是json和xml,下面我們來看看如何用php來封裝一個返回這兩種格式資料的類
我們先定義一個響應類
class response{}
1、以json格式返回資料
json格式返回資料比較簡單,直接將我們後台擷取到的資料,以標準json格式返回給請求端即可
//按json格式返回資料public static function json($code,$message,$data=array()){ if(!is_numeric($code)){ return ''; } $result=array( "code"=>$code, "message"=>$message, "data"=>$data ); echo json_encode($result);}
2、以xml格式返回資料
這種方式需要遍曆data裡面的資料,如果資料裡有數組還要遞迴遍曆。還有一種特殊情況,當數組的下標為數字時,xml格式會報錯,需要將xml中數字標籤替換
//按xml格式返回資料 public static function xmlEncode($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'?>"; $xml.="<root>"; $xml.=self::xmlToEncode($result); $xml.="</root>"; echo $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}>"; } return $xml; }}
3、將兩種格式封裝為一個方法,完整代碼如下:
class response{ public static function show($code,$message,$data=array(),$type='json'){ /** *按綜合方式輸出通訊資料 *@param integer $code 狀態代碼 *@param string $message 提示資訊 *@param array $data 資料 *@param string $type 資料類型 *return string */ if(!is_numeric($code)){ return ''; } $result=array( "code"=>$code, "message"=>$message, "data"=>$data ); if($type=='json'){ self::json($code,$message,$data); exit; }elseif($type=='xml'){ self::xmlEncode($code,$message,$data); exit; }else{ //後續添加其他格式的資料 } } //按json格式返回資料 public static function json($code,$message,$data=array()){ if(!is_numeric($code)){ return ''; } $result=array( "code"=>$code, "message"=>$message, "data"=>$data ); echo json_encode($result); } //按xml格式返回資料 public static function xmlEncode($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'?>"; $xml.="<root>"; $xml.=self::xmlToEncode($result); $xml.="</root>"; echo $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}>"; } return $xml; }}$data=array(1,231,123465,array(9,8,'pan'));response::show(200,'success',$data,'json');
這樣我們調用show方法時,需要傳遞四個參數,第四個參數為想要返回的資料格式,預設為json格式,效果如下:
我們再調用一次show方法,以xml格式返回資料:
response::show(200,'success',$data,'xml');
效果如下:
這樣我們就完成了對這兩種資料格式的封裝,可以隨意返回這兩種格式的資料了