本文主要是介绍PHP DOM操作xml文档,删除一个,遍历删除所有(注意不能一边遍历一边删除),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<?php
//[需求1]:删除第二本书的year节点
$dom = new DOMDocument('1.0','utf-8');
$dom->load('bookstore.xml');
//找到第二本书的year元素
$year = $dom->getElementsByTagName('year')->item(1);
$year->parentNode->removeChild($year); //通过父结点来删除
$dom->save('dom_delete1_book.xml');
dom_delete2.php(循环遍历删除所有,注意有陷阱(删除会导致更新文档,不能一边遍历一边删除)):
<?php
//[需求1]:删除所有书籍的year节点
$dom = new DOMDocument('1.0','utf-8');
$dom->load('bookstore1.xml');
//找到所有书的year元素
$years = $dom->getElementsByTagName('year');//循环删除
/*一边遍历一边删除会出错(隔行删除)。原因:删除的时候会导致更新整个文档,然后继续遍历的时候就会出错。
foreach ($years as $year) {
//读取year节点下的子节点值做相应判断$source = $year->getElementsByTagName("source")->item(0)->nodeValue; //读取节点值,source$translations = $year->getElementsByTagName("translation")->item(0)->attributes->item(0)->nodeValue; //节点属性值 type$translation = $year->getElementsByTagName("translation")->item(0)->nodeValue;// 读取节点值,translation
if($source ==XXXXXX){$temp[] = $year; //删除后更新文档,并不会影响temp[]。}
}*///先遍历 保存。(不能一边遍历一边删除)
$temp = array();
foreach ($years as $year) {//读取year节点下的子节点值做相应判断$source = $year->getElementsByTagName("source")->item(0)->nodeValue; //读取节点值,source$translations = $year->getElementsByTagName("translation")->item(0)->attributes->item(0)->nodeValue; //节点属性值 type$translation = $year->getElementsByTagName("translation")->item(0)->nodeValue;// 读取节点值,translation
$num=$year->getElementsByTagName("location")->length;//获得location节点的个数
if($source ==XXXXXX){$temp[] = $year; //删除后更新文档,并不会影响temp[]。}}
//再循环删除
foreach ($temp as $v) {$v->parentNode->removeChild($v);
}
$dom->save('dom_delete2_book.xml');
?>
这篇关于PHP DOM操作xml文档,删除一个,遍历删除所有(注意不能一边遍历一边删除)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!