设为首页收藏本站language→→ 语言切换

鸿鹄论坛

 找回密码
 论坛注册

QQ登录

先注册再绑定QQ

查看: 1730|回复: 0
收起左侧

使用PHP5 DOM-XML创建和解析XML文件

[复制链接]
发表于 2010-2-24 13:44:10 | 显示全部楼层 |阅读模式
<DIV class=content><>先用PHP5创建一个xml文件</P><RE><?php$dom = new DomDocument("1.0");$root = $dom ->createElement("html");$title = $dom -&gt; createElement("title");$meta = $dom -&gt; createElement("meta");$head = $dom -&gt; createElement("head");$titleText = $dom -&gt; createTextNode("this is a title");$metaText = $dom -&gt; createTextNode("this is a meta");$table = $dom -&gt; createElement("table");$tr = $dom -&gt; createElement("tr");$td = $dom -&gt; createElement("td");$tdText = $dom -&gt; createTextNode("words");$root = $dom -&gt; appendChild($root);$head = $root -&gt; appendChild($head);$title = $head -&gt; appendChild($title);$meta = $head -&gt; appendChild($meta);$comment = $title -&gt; appendChild($titleText);$meta -&gt; appendChild($metaText);$td -&gt; appendChild($tdText);$tr -&gt; appendChild($td);$table -&gt; appendChild($tr);$root -&gt; appendChild($table);$dom -&gt; save("test5.xml");echo "<HR><A href='\"test5.xml\"'>查看test5.xml</A>";?&gt;</PRE><>test5.xml</P><RE><?xml version="1.0"?><HTML><HEAD><META>this is a meta</META><TABLE><TBODY><TR><TD>words</TD></TR></TBODY></TABLE></PRE><>解析test5.xml</P><RE><?php//首先要创建一个DOMDocument对象$dom = new DomDocument("1.0");//然后载入XML文件$dom -> load("test5.xml");//向DOM中写入新数据$tr = $dom -&gt; createElement("tr");$td = $dom -&gt; createElement("td");$tdText = $dom -&gt; createTextNode("hello world");$td -&gt; appendChild($tdText);$tr -&gt; appendChild($td);$dom -&gt; documentElement -&gt; getElementsByTagName("table") -&gt; item(0) -&gt; appendChild($tr);//向DOM中写入新数据$tr2 = $dom -&gt; createElement("tr");$td2 = $dom -&gt; createElement("td");$tdText2 = $dom -&gt; createTextNode("hello world too");$td2 -&gt; appendChild($tdText2);$tr2 -&gt; appendChild($td2);$xpath = new domxpath($dom);$trs = $xpath -&gt; query("/html/table");$trs -&gt; item(0) -&gt; appendChild($tr2);$dom -&gt; save("newfile.xml");echo "<HR><A href='\"newfile.xml\"'>查看newfile.xml</A>";print "<HR>取得所有的td元素<BR>";$tds = $dom -&gt; getElementsByTagName("td");foreach ($tds as $nodes){        print $nodes -&gt; textContent."<BR>";}echo "<HR>使用XPath查询的td节点结果:<HR>";$tdss = $xpath -&gt; query("/html/table/tr");foreach ($tdss as $nodes){        print $nodes -&gt; textContent."<BR>";}?&gt;</PRE></DIV>
您需要登录后才可以回帖 登录 | 论坛注册

本版积分规则

QQ|Archiver|手机版|小黑屋|sitemap|鸿鹄论坛 ( 京ICP备14027439号 )  

GMT+8, 2024-11-23 01:55 , Processed in 0.056084 second(s), 10 queries , Redis On.  

  Powered by Discuz!

  © 2001-2024 HH010.COM

快速回复 返回顶部 返回列表