微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP XML按名称删除元素和所有子元素

我有一个XML文件结构如下:

<root>
  <featured>
    <title></title>
    <tweet></tweet>
    <img></img>
  </featured>
</root> 

元素是动态添加的,用户需要在某些场合删除元素的选项,

我尝试了一些代码变体,包括

        $featureddel = $xpath->query('//featured');

while ( $featureddel->hasChildNodes()){
$featureddel->removeChild($featureddel->childNodes->item(0));
}

这给了我一个错误

PHP Fatal error: Call to undefined method DOMNodeList::hasChildNodes() 

我也尝试过:

$featureddel= $dom->getElementsByTagName('featured');
$featureddel->parentNode->removeChild($featureddel);

返回:

PHP Fatal error: Call to a member function removeChild() on a non-object

解决方法:

DOMElement :: getElementsByTagName和DOMXPath :: query都返回一个DOMNodeList.您的代码似乎期待单个DOMNode.尝试这个:

$featureddel = $xpath->query('//featured');
// OR:
// $featuredde1 = $dom->getElementsByTagName('featured');

foreach ($featuredde1 as $node) {
    $node->parentNode->removeChild($node);
}

编辑:这个确切的代码按预期工作(PHP 5.3,Debian Squeeze):

<?PHP 
$xml = '<root>
  <featured>
    <title></title>
    <tweet></tweet>
    <img></img>
  </featured>
</root>';    
$dom = new DOMDocument();
$dom->loadXML($xml);
$featuredde1 = $dom->getElementsByTagName('featured');

foreach ($featuredde1 as $node) {
    $node->parentNode->removeChild($node);
}
echo $dom->saveXML();

输出是:

<?xml version="1.0"?>
<root>

</root>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。