XML作为数据交换的标记语言,以其低成本和速度快的优点,很快的得到大部分语言的支持。其中PHP就是一种的一个。现在以例子的方式,演示在PHP操作XML文件。
XML文件的源代码如下:
<?xml version="1.0" encoding="GB2312"?>
<books>
<book id="1">
<author sex="男">王志刚</author>
<publisher>人民邮电出版社</publisher>
<title>JAVA</title>
</book>
<book>
<author sex="男">吕小强</author>
<publisher>海燕出版社</publisher>
<title>JSP</title>
</book>
</books>
PHP页面的脚本程序如下:
<?php
$doc = new DOMDocument("1.0");
$doc->load("book.xml");
$node =$doc->createElement("book");
$id=$doc->createAttribute("id");
$idText=$doc->createTextNode("3");
$id->appendChild($idText);
$node->appendChild($id);
$author=$doc->createElement("author");
$author=$node->appendChild($author);
$authorText=$doc->createTextNode("df");
$author->appendChild($authorText);
$title=$doc->createElement("title");
$title=$node->appendChild($title);
$titleText=$doc->createTextNode("C++");
$title->appendChild($titleText);
$doc->getElementsByTagName('book')->item(0)->appendChild($node);
$doc->save("nn.xml");
echo "<hr/><a href=\"nn.xml\">查看nn.xml</a>";
?>
上述的PHP操作,主要完成的是添加XML文件的节点数据。