gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:44:05 25 4
gpt4 key购买 nike

我有一个结构如下的 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::getElementsByTagNameDOMXPath::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>

关于PHP XML 按名称删除元素和所有子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5731879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com