php生成xml简单实例代码


Posted in PHP onDecember 16, 2009

当处理基于XML应用程序时,开发者经常需要建立XML编码数据结构。例如,Web中基于用户输入的XML状态模板,服务器请求XML语句,以及基于运行时间参数的客户响应。
尽管XML数据结构的构建比较费时,但如果使用成熟的PHP DOM应用程序接口,一切都会变得简单明了。本文将向你介绍PHP DOM应用程序接口的主要功能,演示如何生成一个正确的XML完整文件并将其保存到磁盘中。
创建文档类型声明
一般而言,XML声明放在文档顶部。在PHP中声明十分简单:只需实例化一个DOM文档类的对象并赋予它一个版本号。查看程序清单A:
程序清单 A

<?php 
// create doctype 
$dom = new DOMDocument("1.0"); 
// display document in browser as plain text 
// display document in browser as plain text 
// for readability purposes 
header("Content-Type: text/plain"); 
// save and display tree 
echo $dom->saveXML(); 
?>

请注意DOM文档对象的saveXML()方法。稍后我再详细介绍这一方法,现在你只需要简单认识到它用于输出XML文档的当前快照到一个文件或浏览器。在本例,为增强可读性,我已经将ASCII码文本直接输出至浏览器。在实际应用中,可将以text/XML头文件发送到浏览器。
如在浏览器中查看输出,你可看到如下代码:
<?xml version="1.0"?>
添加元素和文本节点
XML真正强大的功能是来自其元素与封装的内容。幸运的是,一旦你初始化DOM文档,很多操作变得很简单。此过程包含如下两步骤:
对想添加的每一元素或文本节点,通过元素名或文本内容调用DOM文档对象的createElement()或createTextNode()方法。这将创建对应于元素或文本节点的新对象。
通过调用节点的appendChild()方法,并把其传递给上一步中创建的对象,并在XML文档树中将元素或文本节点添加到父节点。
以下范例将清楚地演示这2步骤,请查看程序清单B。
程序清单 B
<?php 
// create doctype 
$dom = new DOMDocument("1.0"); 
// display document in browser as plain text 
// for readability purposes 
header("Content-Type: text/plain"); 
// create root element 
$root = $dom->createElement("toppings"); 
$dom->appendChild($root); 
// create child element 
$item = $dom->createElement("item"); 
$root->appendChild($item); 
// create text node 
$text = $dom->createTextNode("pepperoni"); 
$item->appendChild($text); 
// save and display tree 
echo $dom->saveXML(); 
?>

这 里,我首先创建一个名字为<toppings>的根元素,并使它归于XML头文件中。然后,我建立名为<item>的元素并使它 归于根元素。最后,我又创建一个值为“pepperoni”的文本节点并使它归于<item>元素。最终结果如下:
<?xml version="1.0"?> 
<toppings> 
<item>pepperoni</item> 
</toppings>

如果你想添加另外一个topping,只需创建另外一个<item>并添加不同的内容,如程序清单C所示。
程序清单C
<?php 
// create doctype 
$dom = new DOMDocument("1.0"); 
// display document in browser as plain text 
// for readability purposes 
header("Content-Type: text/plain"); 
// create root element 
$root = $dom->createElement("toppings"); 
$dom->appendChild($root); 
// create child element 
$item = $dom->createElement("item"); 
$root->appendChild($item); 
// create text node 
$text = $dom->createTextNode("pepperoni"); 
$item->appendChild($text); 
// create child element 
$item = $dom->createElement("item"); 
$root->appendChild($item); 
// create another text node 
$text = $dom->createTextNode("tomato"); 
$item->appendChild($text); 
// save and display tree 
echo $dom->saveXML(); 
?>

以下是执行程序清单C后的输出:
<?xml version="1.0"?> 
<toppings> 
<item>pepperoni</item> 
<item>tomato</item> 
</toppings>

添加属性
通过使用属性,你也可以添加适合的信息到元素。对于PHP DOM API,添加属性需要两步:首先用DOM文档对象的createAttribute()方法创建拥有此属性名字的节点,然后将文档节点添加到拥有属性值的属性节点。详见程序清单D。
程序清单 D
<?php 
// create doctype 
$dom = new DOMDocument("1.0"); 
// display document in browser as plain text 
// for readability purposes 
header("Content-Type: text/plain"); 
// create root element 
$root = $dom->createElement("toppings"); 
$dom->appendChild($root); 
// create child element 
$item = $dom->createElement("item"); 
$root->appendChild($item); 
// create text node 
$text = $dom->createTextNode("pepperoni"); 
$item->appendChild($text); 
// create attribute node 
$price = $dom->createAttribute("price"); 
$item->appendChild($price); 
// create attribute value node 
$priceValue = $dom->createTextNode("4"); 
$price->appendChild($priceValue); 
// save and display tree 
echo $dom->saveXML(); 
?>

输出如下所示:
<?xml version="1.0"?> 
<toppings> 
<item price="4">pepperoni</item> 
</toppings>

添加CDATA模块和过程向导
虽然不经常使用CDATA模块和过程向导,但是通过调用DOM文档对象的createCDATASection()和createProcessingInstruction()方法, PHP API 也能很好地支持CDATA和过程向导,请见程序清单E。
程序清单 E
<?php 
// create doctype 
// create doctype 
$dom = new DOMDocument("1.0"); 
// display document in browser as plain text 
// for readability purposes 
header("Content-Type: text/plain"); 
// create root element 
$root = $dom->createElement("toppings"); 
$dom->appendChild($root); 
// create child element 
$item = $dom->createElement("item"); 
$root->appendChild($item); 
// create text node 
$text = $dom->createTextNode("pepperoni"); 
$item->appendChild($text); 
// create attribute node 
$price = $dom->createAttribute("price"); 
$item->appendChild($price); 
// create attribute value node 
$priceValue = $dom->createTextNode("4"); 
$price->appendChild($priceValue); 
// create CDATA section 
$cdata = $dom->createCDATASection(" Customer requests that pizza be sliced into 16 square pieces "); 
$root->appendChild($cdata); 
// create PI 
$pi = $dom->createProcessingInstruction("pizza", "bake()"); 
$root->appendChild($pi); 
// save and display tree 
echo $dom->saveXML(); 
?>

输出如下所示:
<?xml version="1.0"?> 
<toppings> 
<item price="4">pepperoni</item> 
<![CDATA[ 
Customer requests that pizza be sliced into 16 square pieces 
]]> 
<?pizza bake()?> 
</toppings>

保存结果
一旦已经实现你的目标,就可以将结果保存在一个文件或存储于PHP的变量。通过调用带有文件名的save()方法可以将结果保存在文件中,而通过调用saveXML()方法可存储于PHP的变量。请参考以下实例(程序清单F):
程序清单 F
<?php 
// create doctype 
$dom = new DOMDocument("1.0"); 
// create root element 
$root = $dom->createElement("toppings"); 
$dom->appendChild($root); 
$dom->formatOutput=true; 
// create child element 
$item = $dom->createElement("item"); 
$root->appendChild($item); 
// create text node 
$text = $dom->createTextNode("pepperoni"); 
$item->appendChild($text); 
// create attribute node 
$price = $dom->createAttribute("price"); 
$item->appendChild($price); 
// create attribute value node 
$priceValue = $dom->createTextNode("4"); 
$price->appendChild($priceValue); 
// create CDATA section 
$cdata = $dom->createCDATASection(" Customer requests that pizza be 
sliced into 16 square pieces "); 
$root->appendChild($cdata); 
// create PI 
$pi = $dom->createProcessingInstruction("pizza", "bake()"); 
$root->appendChild($pi); 
// save tree to file 
$dom->save("order.xml"); 
// save tree to string 
$order = $dom->save("order.xml"); 
?>

下面是实际的例子,大家可以测试下。
xml.php(生成xml)
<? 
$conn = mysql_connect('localhost', 'root', '123456') or die('Could not connect: ' . mysql_error()); 
mysql_select_db('vdigital', $conn) or die ('Can\'t use database : ' . mysql_error()); 
$str = "SELECT id,username FROM `admin` GROUP BY `id` ORDER BY `id` ASC"; 
$result = mysql_query($str) or die("Invalid query: " . mysql_error()); 
if($result) 
{ 
$xmlDoc = new DOMDocument(); 
if(!file_exists("01.xml")){ 
$xmlstr = "<?xml version='1.0' encoding='utf-8' ?><message></message>"; 
$xmlDoc->loadXML($xmlstr); 
$xmlDoc->save("01.xml"); 
} 
else { $xmlDoc->load("01.xml");} 
$Root = $xmlDoc->documentElement; 
while ($arr = mysql_fetch_array($result)){ 
$node1 = $xmlDoc->createElement("id"); 
$text = $xmlDoc->createTextNode(iconv("GB2312","UTF-8",$arr["id"])); 
$node1->appendChild($text); 
$node2 = $xmlDoc->createElement("name"); 
$text2 = $xmlDoc->createTextNode(iconv("GB2312","UTF-8",$arr["username"])); 
$node2->appendChild($text2); 
$Root->appendChild($node1); 
$Root->appendChild($node2); 
$xmlDoc->save("01.xml"); 
} 
} 
mysql_close($conn); 
?>

test.php(应用测试)
<? 
$xmlDoc = new DOMDocument(); 
$xmlDoc->load("http://localhost/xml/xml.php"); 
$x=$xmlDoc->getElementsByTagName('name'); 
for ($i=0; $i<=$x->length-1; $i++) 
{ 
if(strpos($x->item($i)->nodeValue,"fang")!==false) 
{ 
echo $x->item($i)->parentNode->childNodes->item(1)->nodeValue; 
} 
} 
?>
PHP 相关文章推荐
其他功能
Oct 09 PHP
使用PHP遍历文件夹与子目录的函数代码
Sep 26 PHP
destoon实现调用热门关键字的方法
Jul 15 PHP
php实现无限级分类
Dec 24 PHP
php可应用于面包屑导航的递归寻找家谱树实现方法
Feb 02 PHP
PHP模板引擎Smarty内建函数foreach,foreachelse用法分析
Apr 11 PHP
PHP魔术方法以及关于独立实例与相连实例的全面讲解
Oct 18 PHP
php array_key_exists() 与 isset() 的区别
Oct 24 PHP
静态html文件执行php语句的方法(推荐)
Nov 21 PHP
PHP封装返回Ajax字符串和JSON数组的方法
Feb 17 PHP
PHP基于IMAP收取邮件的方法示例
Aug 07 PHP
php基于环形链表解决约瑟夫环问题示例
Nov 07 PHP
PHP 基本语法格式
Dec 15 #PHP
php遍历目录viewDir函数
Dec 15 #PHP
php csv操作类代码
Dec 14 #PHP
PHP开发过程中常用函数收藏
Dec 14 #PHP
将文件夹压缩成zip文件的php代码
Dec 14 #PHP
php入门教程 精简版
Dec 13 #PHP
php实现的仿阿里巴巴实现同类产品翻页
Dec 11 #PHP
You might like
用Socket发送电子邮件(利用需要验证的SMTP服务器)
2006/10/09 PHP
Mysql的GROUP_CONCAT()函数使用方法
2008/03/28 PHP
PHP中用hash实现的数组
2011/07/17 PHP
php数组函数序列之array_key_exists() - 查找数组键名是否存在
2011/10/29 PHP
PHP判断一个数组是另一个数组子集的方法详解
2017/07/31 PHP
javascript innerHTML、outerHTML、innerText、outerText的区别
2008/11/24 Javascript
让IE8支持DOM 2(不用框架!)
2009/12/31 Javascript
javascript学习笔记(三)显示当时时间的代码
2011/04/08 Javascript
javascript中IE浏览器不支持NEW DATE()带参数的解决方法
2012/03/01 Javascript
jQuery $.get 的妙用 访问本地文本文件
2012/07/12 Javascript
node.js中的console.timeEnd方法使用说明
2014/12/09 Javascript
jQuery实现ctrl+enter(回车)提交表单
2015/10/19 Javascript
JavaScript计划任务后台运行的方法
2015/12/18 Javascript
解决js函数闭包内存泄露问题的办法
2016/01/25 Javascript
js+css实现select的美化效果
2016/03/24 Javascript
javascript基础知识讲解
2017/01/11 Javascript
vue 里面使用axios 和封装的示例代码
2017/09/01 Javascript
JavaScript实现烟花绽放动画效果
2020/08/04 Javascript
基于Python实现文件大小输出
2016/01/11 Python
Python Socket传输文件示例
2017/01/16 Python
Python装饰器实现几类验证功能做法实例
2017/05/18 Python
Python 3.8新特征之asyncio REPL
2019/05/28 Python
Django之编辑时根据条件跳转回原页面的方法
2019/08/21 Python
Python3离线安装Requests模块问题
2019/10/13 Python
Python绘制二维曲线的日常应用详解
2019/12/04 Python
基于Python+QT的gui程序开发实现
2020/07/03 Python
几个解决兼容IE6\7\8不支持html5标签的几个方法
2013/01/07 HTML / CSS
西海岸男士和男童服装:Johnnie-O
2018/03/15 全球购物
建筑毕业生自我鉴定
2013/10/18 职场文书
安全生产管理合理化建议书
2014/03/12 职场文书
老公保证书范文
2014/04/29 职场文书
节能减耗标语
2014/06/21 职场文书
工作收入住址证明
2014/10/28 职场文书
庆六一开幕词
2015/01/29 职场文书
小学教师个人总结
2015/02/05 职场文书
解决IIS7下无法绑定https主机的问题
2022/04/29 Servers