DOMElement does not seem to be removed from DOMNodeList

点点圈 提交于 2020-01-04 05:26:46

问题


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(){} 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:

Keep in mind that DOMNodelists are "live" - changes to the document or node that the DOMNodelist was derived from will be reflected in the DOMNodelist.

You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards

But it doesn't happen!

No errors occur, $result equals that exact element #0 (meaning removeChild() has done it's job correctly)

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

P.S. of course, is such situation one can always just use continue to jump through iteration, but what about deleting?


回答1:


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.



来源:https://stackoverflow.com/questions/46448006/domelement-does-not-seem-to-be-removed-from-domnodelist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!