php產生XML資料
1)組裝字串
2)使用系統類別
- DomDocument
- XMLWriter
- SimpleXML
這裡以第一種方法舉例:
$code, 'message' => $message, 'date' => $data ); echo json_encode($result); exit; } public static function xml(){ header("content-type:text/xml"); $xml = "\n"; $xml .= "\n"; $xml .="200\n"; $xml .="資料返回成功\n"; $xml .="\n"; $xml .="1\n"; $xml .="ceshi\n"; $xml .="\n"; $xml .= "\n"; echo $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 .="\n"; $xml .= self::xmlToEncode($result); 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; //遞迴,如果value是數組,遞迴輸出節點。 $xml .= "\n"; } return $xml; }}$arr = array( 'id' => 1, 'name' => 'xxx', 'type' => array(4,5,6), 'test' => array(1,25,345=>array(123,'zifuchuan')));//<0>4 4//Response::json(200,'資料返回成功',$arr);//Response::xml();Response::xmlEncode(200,'success',$arr);
以上就介紹了封裝通訊介面資料的方法-xml,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。