php對xml文件中節點的删除\修改
使用getElementsByTagName()方法删除\修改XML節點
三個文件:
1.root.=xml
2.remove.php —— 删除節點
3.replace.php —— 修改節點
root.xml
按下”閱讀更多”看全文
root.xml
<root>
<child1>child1 content</child1>
<child2>child2 content</child2>
<child3>child3 content</child3>
</root>
remove.php
<?php
$xml_str = file_get_contents("root.xml"); //root.xml為檔名
$doc = DOMDocument::loadXML($xml_str); //載入此字串
//取得元素$child2
$root = $doc->documentElement;
$child2 = $root->;getElementsByTagName("child2")->;item(0);
//刪除$child2
$root->removeChild($child2);
//存檔
$doc->formatOutput = true;
$doc->saveXML();
$doc->save("root.xml");
?>
replace.php
<?php
$xml_str = file_get_contents("root.xml"); //將root.xml為檔名
$doc = DOMDocument::loadXML($xml_str); //載入字串
//取得元素$child3
$root = $doc->documentElement;
$child3 = $root->getElementsByTagName("child3")->item(0);
//建立一個newchild元素來替代child3
$root->replaceChild(new DOMElement("newchild", "new content"), $child3);
//存檔
$doc->formatOutput = true;
$doc->saveXML();
$doc->save("root.xml");
?>
使用使用XPath刪除\修改節點
1.xml.xml
2.re.php —— 取代\刪除節點
3.replace.xml —— 修改節點後的XML
4.remove.xml —— 刪除節點後的XML
xml.xml
<?xml version="1.0"?>
<books>
<book>
<author>Jack Herrington</author>
<title>PHP Hacks</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>
re.php
<?php
$dom = new DomDocument();
$dom -> load("xml.xml");
$xpath = new domxpath($dom);
//修改節點
$oldtitle = $xpath->query("/books/book/title")->item(0);
$newtitle = $dom->createElement("title");
$newtitle->appendChild(new DOMText("NEW"));
$oldtitle->parentNode->replaceChild($newtitle, $oldtitle);
$dom->save("replace.xml");
//刪除節點
$oldtitle = $xpath->query("/books/book/title")->item(1);
$oldtitle->parentNode->removeChild($oldtitle);
$dom->save("remove.xml");
?>
replace.xml
<?xml version="1.0"?>
<books>
<book>
<author>Jack Herrington</author>
<title>NEW</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>
remove.xml
<?xml version="1.0"?>
<books>
<book>
<author>Jack Herrington</author>
<title>NEW</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<publisher>O'Reilly</publisher>
</book>
</books>
0 意見:
張貼留言