php中操作xml文檔我們會使用SimpleXMLElement函數,我們先瞭解一下SimpleXMLElement函數用法
SimpleXML 函數允許您把 XML 轉換為對象。
通過普通的屬性選取器或數組迭代器,可以處理這個對象,就像處理任何其他對象一樣。
例子
xml文檔格式
| 代碼如下 |
複製代碼 |
<?php error_reporting(E_ALL ^ E_NOTICE); $op=$_GET['op']; $op || $op='list'; $filename='guestbook.xml'; if(is_file($filename)){ $gb=simplexml_load_file($filename); }else{ $gb=new SimpleXMLElement("<?xml version='1.0' encoding='utf-8'?><guestbook></guestbook>"); } if($op=='list'){ header("Content-Type:text/html;charset=utf-8"); if(is_object($gb)){ echo "<table>"; echo "<tr><th>ID</th><th>使用者</th><th>標題</th><th>標題</th><th>內容</th><th>時間</th><th>IP</th></tr>"; foreach($gb->item as $v){ echo "<tr>"; echo "<td>".htmlspecialchars($v->id)."</td><td>".htmlspecialchars($v->user)."</td><td>".htmlspecialchars($v->title)."</td><td>".htmlspecialchars($v->content)."</td><td>".date("Y-m-d H:i",intval($v->time))."</td><td>".htmlspecialchars($v->ip)."</td>"; } echo '<table>'; } echo "<div><a href='guestbook.php?op=add'>添加</a></div>"; }elseif($op=='save'){ if(@$_POST['user']){ $user=$_POST['user']; $title=$_POST['title']; $content=$_POST['content']; /* $id=@count($gb->item); $nextid=$id+1; */ $nextid=1; foreach($gb->item as $v){ $idarr[]=(int)$v->id; } $nextid=max($idarr)+1; $item=$gb->addChild('item'); $item->addChild("id",$nextid); $item->addChild('user',$user); $item->addChild('title',$title); $item->addChild('content',$content); $item->addChild('time',time()); $item->addChild('ip',$_SERVER['REMOTE_ADDR']); $gb->asXML($filename); //跳轉頁,中間頁 header("Location: guestbook.php?op=list"); die; } }elseif($op=='add'){ ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> </head> <body> <form action="guestbook.php?op=save" method="post"> <div>使用者:<input type="text" name="user"></div> <div>標題:<input type="text" name="title"></div> <div>留言:<textarea name="content" id="" cols="30" rows="10"></textarea></div> <div><input type="submit" value="提交留言"></div> </form> </body> </html> <?php } ?> |