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

Bob*_*ing 2 php xml dom

我有一个结构为的 XML 文件:

<root>
  <featured>
    <title></title>
    <tweet></tweet>
    <img></img>
  </featured>
</root> 
Run Code Online (Sandbox Code Playgroud)

元素是动态添加的,用户需要选择在某些情况下删除元素,

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

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

while ( $featureddel->hasChildNodes()){
$featureddel->removeChild($featureddel->childNodes->item(0));
}
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误:

PHP Fatal error: Call to undefined method DOMNodeList::hasChildNodes() 
Run Code Online (Sandbox Code Playgroud)

我也试过:

$featureddel= $dom->getElementsByTagName('featured');
$featureddel->parentNode->removeChild($featureddel);
Run Code Online (Sandbox Code Playgroud)

返回:

PHP Fatal error: Call to a member function removeChild() on a non-object
Run Code Online (Sandbox Code Playgroud)

San*_*hal 5

双方DOMElement::getElementsByTagNameDOMXPath::query返回DOMNodeList。您的代码似乎需要一个DOMNode。尝试这个:

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

foreach ($featuredde1 as $node) {
    $node->parentNode->removeChild($node);
}
Run Code Online (Sandbox Code Playgroud)

编辑:这个确切的代码对我来说按预期工作(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();
Run Code Online (Sandbox Code Playgroud)

输出是:

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

</root>
Run Code Online (Sandbox Code Playgroud)