PHP XML操作的各种方法解析(比较详细)(5)


<?xml version=”1.0″?>
<threads>
<thread>
<title>这里是留言的标题</title>
<author>这里是留言者</author>
<content>这里是留言内容</content>
</thread>
</threads>


4.2 提交页面的编写
提交留言页面由两个页面组成。一个是让访问者用来书写留言的表单的 HTML文件,一个是用来处理访问者输入的 PHP脚本。表单的 HTML代码如下所示。

复制代码 代码如下:


<html>
<head>
<title>发表新的留言</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312″>
</head>
<body>
<H1><p align=”center”>发表新的留言</p></H1>
<form name=”form1″ method=”post” action=”Post.php”>
<table width=”500″ border=”0″ align=”center” cellpadding=”0″ cellspacing=”0″>
<tr>
<td>标题</td>
<td><input name=”title” type=”text” id=”title” size=”50″></td>
</tr>
<tr>
<td>作者</td>
<td><input name=”author” type=”text” id=”author” size=”20″></td>
</tr>
<tr>
<td>内容</td>
<td><textarea name=”content” cols=”50″ rows=”10″ id=”content”></textarea></td>
</tr>
</table>
<p align=”center”>
<input type=”submit” value=”Submit”>
<input type=”reset” value=”Reset”>
</p>
</form>
</body>
</html>


对于用来处理用户输入的 PHP脚本,其基本逻辑是首先创建一个 DOM对象,然后读取 XML文件中的 XML数据,接下来在 XML对象上创建新的节点并将用户的输入储存起来,最后将 XML数据输出到原来的 XML文件中。具体实现代码如下所示。

复制代码 代码如下:


<?php
$guestbook = new DomDocument(); //创建一个新的 DOM对象
$guestbook->load('DB/guestbook.xml'); //读取 XML数据
$threads = $guestbook->documentElement; //获得 XML结构的根
//创建一个新 thread节点
$thread = $guestbook->createElement('thread');
$threads->appendChild($thread);
//在新的 thread节点上创建 title标签
$title = $guestbook->createElement('title');
$title->appendChild($guestbook->createTextNode($_POST['title']));
$thread->appendChild($title);
//在新的 thread节点上创建 author标签
$author = $guestbook->createElement('author');
$author->appendChild($guestbook->createTextNode($_POST['author']));
$thread->appendChild($author);
//在新的 thread节点上创建 content标签
$content = $guestbook->createElement('content');
$content->appendChild($guestbook->createTextNode($_POST['content']));
$thread->appendChild($content);
//将 XML数据写入文件
$fp = fopen(”DB/guestbook.xml”, “w”);
if(fwrite($fp, $guestbook->saveXML()))
echo “留言提交成功”;
else
echo “留言提交失败”;
fclose($fp);
?>


在浏览器中运行上述 HTML文件并填写适当的留言内容,如图 2所示。

PHP XML操作的各种方法解析(比较详细)

 
图 2 发表新留言界面
单击【Submit】按钮后,XML文件中的内容如下所示。
可以看到 XML文件中已经将留言存储起来了。
4.3 显示页面的编写
显示页面可以使用前面介绍的 SimpleXML组件很容易的实现,具体实现代码如下所示。

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/4c00cb4e32706269e5d466b2174f48f7.html