先用PHP5创建一个xml文件
<?php
$dom = new DomDocument("1.0");
$root = $dom -> createElement("html");
$title = $dom -> createElement("title");
$meta = $dom -> createElement("meta");
$head = $dom -> createElement("head");
$titleText = $dom -> createTextNode("this is a title");
$metaText = $dom -> createTextNode("this is a meta");
$table = $dom -> createElement("table");
$tr = $dom -> createElement("tr");
$td = $dom -> createElement("td");
$tdText = $dom -> createTextNode("words");
$root = $dom -> appendChild($root);
$head = $root -> appendChild($head);
$title = $head -> appendChild($title);
$meta = $head -> appendChild($meta);
$comment = $title -> appendChild($titleText);
$meta -> appendChild($metaText);
$td -> appendChild($tdText);
$tr -> appendChild($td);
$table -> appendChild($tr);
$root -> appendChild($table);
$dom -> save("test5.xml");
echo "<hr/><a href=\"test5.xml\">查看test5.xml</a>";
?>
test5.xml
<?xml version="1.0"?>
<html>
<head>
<title>this is a title</title>
<meta>this is a meta</meta>
</head>
<table>
<tr>
<td>words</td>
</tr>
</table>
</html>
解析test5.xml
<?php
//首先要创建一个DOMDocument对象
$dom = new DomDocument("1.0");
//然后载入XML文件
$dom -> load("test5.xml");
//向DOM中写入新数据
$tr = $dom -> createElement("tr");
$td = $dom -> createElement("td");
$tdText = $dom -> createTextNode("hello world");
$td -> appendChild($tdText);
$tr -> appendChild($td);
$dom -> documentElement -> getElementsByTagName("table") -> item(0) -> appendChild($tr);
//向DOM中写入新数据
$tr2 = $dom -> createElement("tr");
$td2 = $dom -> createElement("td");
$tdText2 = $dom -> createTextNode("hello world too");
$td2 -> appendChild($tdText2);
$tr2 -> appendChild($td2);
$xpath = new domxpath($dom);
$trs = $xpath -> query("/html/table");
$trs -> item(0) -> appendChild($tr2);
$dom -> save("newfile.xml");
echo "<hr/><a href=\"newfile.xml\">查看newfile.xml</a>";
print "<hr>取得所有的td元素<br>";
$tds = $dom -> getElementsByTagName("td");
foreach ($tds as $nodes)
{
print $nodes -> textContent."<br>";
}
echo "<hr/>使用XPath查询的td节点结果:<hr/>";
$tdss = $xpath -> query("/html/table/tr");
foreach ($tdss as $nodes)
{
print $nodes -> textContent."<br>";
}
?>