<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>