似乎没有从DOMNodeList中删除DOMElement [英] DOMElement does not seem to be removed from DOMNodeList
问题描述
请帮忙!
需要删除从 DOMNodeList $ myDivs
中的第一个元素,但实际删除没有发生-元素保留。
Plase, help!
Need to delete 1st element from DOMNodeList $myDivs
, but actual removal dosen't occur - element remains.
$dom = new DOMDocument();
$dom->loadHTML($file);
$xpath = new DOMXPath($dom);
$myDivs = $xpath->query('//div[@data-name|data-price]');
usleep(1);
//Must REVERSE iterate DOMNodeList.
for ($i = $myDivs->length - 1; $i >= 0; $i--) {
//Deleting 1st element of (DOMNodeList) $myDivs, containing advertisement product
if ($i == 0) {
//Removing div element (DOMNode) from DOM? DOMNodeList? Nothing changes
$result = $myDivs->item($i)->parentNode->removeChild($myDivs->item($i));
}
//Adding formatted string of attributes of valid DOMElements (div)
$outputArr[] = printf('%1$s - %2$s, %3$s.<br>',
$myDivs->item($i)->getAttribute('data-name'),
$myDivs->item($i)->getAttribute('data-price'),
$myDivs->item($i)->getAttribute('data-currency'))
?? null;
}
for(){}
反向迭代通过XPath获取的 $ myDivs
并在最后一次迭代( $ i = 0
,元素#0 )DOMElement应该从任何地方(DOM和DOMNodeList)清除,就像从php.net上清除一样:
for(){}
reverse iterates through $myDivs
, fetched by XPath and at last iteration ($i=0
, element #0) DOMElement should be purged from everywhere (DOM and DOMNodeList), as it seems from php.net:
如果您向后迭代,则可以修改甚至删除DOMNodeList中的节点
没有错误发生, $ result
等于确切的元素#0(表示 removeChild()
正确完成了工作)
No errors occur, $result
equals that exact element #0 (meaning removeChild()
has done it's job correctly)
调试时我在 usleep(1);
行和<$ c行得到 $ myDivs-> length = 31
$ c> $ outputArr [] = ... 我仍然有相同长度的 $ myDivs
。
因此,元素#0仍附加在 $ ouputArr
上,而不应该...
While debugging I get $myDivs->length=31
at line usleep(1);
, and at line $outputArr[] =...
I still have same length of $myDivs
.
So, element #0 still gets appended to $ouputArr
, while shouldn't...
看不到我丢失了...
Can't see what I'm missing...
PS当然,这种情况是否总是可以只使用 continue
来跳过迭代,但是删除又如何呢?
P.S. of course, is such situation one can always just use continue
to jump through iteration, but what about deleting?
推荐答案
您未引用官方文档,而是用户提供的评论。从XPath查询返回的DOMNodeList不是实时的。 removeChild
仅将节点从原始文档中删除,而不是从DOMNodeList中删除。
You're not quoting the official documentation but remarks contributed by users. DOMNodeLists returned from XPath queries aren't "live". removeChild
only removes the node from the original document, not from the DOMNodeList.
这篇关于似乎没有从DOMNodeList中删除DOMElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!