1.PHP 生成 XML 数据
① 拼接字符串
② 使用系统类(DomDocument,XMLWriter,SimpleXML)
例1 使用 PHP 系统类中的 DomDocument 类:
createElement('test','This is a root element');$dom->appendChild($element);echo $dom->saveXML();
页面输出
This is a root element
查看源代码显示:
This is a root element
例2 拼接字符串
//修改 http 头信息header("Content-Type:text/xml");//xml头信息$xml = " \n";//根节点开始标签$xml .= "\n";//code$xml .= " ";echo $xml;exit();200
\n"; //message$xml .= "数据返回成功 \n"; //data$xml .= " \n"; $xml .= "1 \n";$xml .= "John \n";$xml .= "\n";//根节点结束标签$xml .= "
页面输出:
This XML file does not appear to have any style information associated with it. The document tree is shown below.200
数据返回成功 1 John
http 响应头信息:
2.XML 方式封装通信接口
$code, 'message' => $message, 'data' => $data ); //修改 http 头信息 header("Content-Type:text/xml"); //xml头信息 $xml = " "; //根节点开始标签 $xml .= ""; $xml .= self::xmlToEncode($result); //根节点结束标签 $xml .= " "; echo $xml; exit(); } //解析$result至xml public static function xmlToEncode($data){ $xml = $attr = ""; foreach($data as $k=>$v){ //如果$k是数字(data(code,message,data中的data)数据里面还含有索引数组),要进行如下判断 if(is_numeric($k)){ $attr = "id='{ $k}'"; $k = 'item '; } $xml .= "<{ $k} { $attr}>"; //如果$v是数组,则递归调用该方法 if(is_array($v)){ $xml .= self::xmlToEncode($v); }else{ $xml .= $v; } $xml .= " "; } return $xml; }}
调用该页面 test.php
$data 第一种情况:
1, 'name'=>'Mary');Response::xml(200,'数据返回成功',$data);
页面输出:
This XML file does not appear to have any style information associated with it. The document tree is shown below.200
数据返回成功 1 Mary
$data 第二种情况
1, 'name'=>'Mary', 'type'=>array(1,3,6) //<0>1 <1>3 <2>6 =>- 1
...);Response::xml(200,'数据返回成功',$data);
页面输出:
This XML file does not appear to have any style information associated with it. The document tree is shown below.200
数据返回成功 1 Mary - 1
- 3
- 6
$data 第三中情况:
1, 'name'=>'Mary', 'type'=>array('a'=>1,'b'=>3,'c'=>6));Response::xml(200,'数据返回成功',$data);
页面输出:
This XML file does not appear to have any style information associated with it. The document tree is shown below.200
数据返回成功 1 Mary 1 3 6