<?php class Response_json_xml{ public static function show($code,$message="",$data=array(),$type){ if(is_null($code)){ return ''; } $data=array( 'code'=>$code, 'message'=>$message, 'data'=>$data ); if($type=="json"){ self::json($code,$message,$data);die; }else if($type=="array"){ var_dump($data);die; }elseif($type=="xml"){ self::xml_encoding($code,$message,$data);die; }else{ //coding.... } } /** *按json方式输出通信 *@param integet $code 状态码 *@param string $message 提示信息 *@param array $data 数据 * return string */ public static function json($code,$message,$data=array()){ if(is_null($code)){ return ''; } $result=array( 'code'=>$code, 'message'=>$message, 'data'=>$data ); echo json_encode($result); die; } /** *按xml方式输出通信 *@param integet $code 状态码 *@param string $message 提示信息 *@param array $data 数据 * return string */ public static function xml_encoding($code,$message,$data=array()){ if(is_null($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::xml_array($result); $xml.="</root> "; echo $xml; } public static function xml_array($result){ $xml=$attr=""; foreach ($result as $key => $value) { if(is_numeric($key)){ $attr=" id='{$key}'"; $key="item"; } $xml.="<{$key}{$attr}> "; $xml.=is_array($value)?self::xml_array($value):$value; $xml.="</{$key}> "; } return $xml; } } $data=array( 'id'=>1, 'name'=>'hgj123', ); $data1=array(1,2,3,11,122); $type=isset($_GET['type'])?$_GET['type']:'json'; Response_json_xml::show(200,'成功',$data,$type);