function __construct() {
//必须调用!
parent::__construct()
}
function addArticle($title) {
$item = $this->createElement("item")
$titlespace = $this->createElement("title")
$titletext = $this->createTextNode($title)
$titlespace->appendChild($titletext)
$item->appendChild($titlespace)
$this->documentElement->appendChild($item)
}
}
$dom = new Articles()
$dom->load("articles.xml")
$dom->addArticle("XML in PHP5")
print $dom->save("newfile.xml")
HTML
本文来自: 脚本之家(www.jb51.net) 详细出处参考:http://www.jb51.net/article/1474.htm
我是用DOMDocument对象来 *** 作xml的 代码如下
<?php//加载xml
$path = $_SERVER["DOCUMENT_ROOT"].'/20150524/book.xml'
//实例化类
$books = new DOMDocument()
//通过方法加载
$books->load($path)
$newItem=$books->createElement('item') //创建新元素
$title=$books->createElement('title') //创建子元素
$title->nodeValue='newtitle'
$newItem->appendChild($title) //把子元素添加到父元素上
$content=$books->createElement('content') //创建子元素
$content->nodeValue='newcontent'
$newItem->appendChild($content) //把子元素添加到父元素上
//添加到第一个节点前
$books->documentElement->insertbefore($newItem,$elements->item(0))
$books->save($path) //保存
?>
添加后 xml文件如下所示
<?xml version="1.0"?><books>
<item>
<title>newTitle</title>
<content>newContent</content>
</item>
<book name="JavaScript: The Defiitive Guide" publisher="O'Reilly Media, Inc.">
<author>David Flanagan</author>
</book>
<book name="PHP anf MySQL Web Development" publisher="Perason Education">
<author>Luke Welling</author>
<author>Laura Thomson</author>
</book>
<book name="HTTP: The Defiitive Guide" publisher="O'Reilly Media, Inc.">
<author>David Courley</author>
<author>Brian Totty</author>
</book>
</books>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)