php 使用对象方式输出XML文件

<?php

	//构造XmlDocument对象 
	$dom=new DOMDocument("1.0","UTF-8");
	//创建最外层元素
	$users=$dom->createElement("users");
	
	
	$conn=new PDO("mysql:dbname=lamp;host=localhost","root","123456");
	$stmt=$conn->prepare("select id,username,phone from user");
	$stmt->execute();
	//分别创建每个元素
	
	while(list($id,$username,$phone)=$stmt->fetch(PDO::FETCH_NUM)){
		$person=$dom->createElement("person");
		//为person标签添加属性
		$person->setAttribute("id",$id);
		//创建username标签 createElement(标签名,文本节点内容);
		$username=$dom->createElement("username",$username);
		//添加到 $person节点 
		$person->appendChild($username);
		$phone=$dom->createElement("phone",$phone);
		$person->appendChild($phone);
		$users->appendChild($person);
	}
	
	$dom->appendChild($users);
	//输出结构
	header("Content-type:text/xml");
	$xmlfile=$dom->saveXML();
	file_put_contents("domuser.xml",$xmlfile);
	echo $xmlfile;
//创建文本节点
//OBJECT->createTextNode()
//OBJECT->createCDATASection //添加文本节点的CDATA段落


你可能感兴趣的:(PHP,xml)