似乎没有从DOMNodeList中删除DOMElement

时间:2017-09-27 12:34:07

标签: php domdocument domxpath

Plase,help!
需要删除来自DOMNodeList $myDivs的第一个元素,但实际删除不会发生 - 元素仍然存在。

$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(){}反向遍历$myDivs,由XPath提取并在最后一次迭代($i=0,元素#0)DOMElement应该从任何地方清除(DOM和DOMNodeList),因为它似乎来自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

但它不会发生!

没有错误发生,$result等于确切的元素#0(意味着removeChild()正确地完成了它的工作)

调试时,我$myDivs->length=31usleep(1);$outputArr[] =...行{} $myDivs$ouputArr的长度相同。 因此,元素#0仍会附加到continue,而不应该...... {/ p>

看不到我错过的东西......

P.S。当然,这样的情况总是可以使用ngModel来跳过迭代,但是删除呢?

1 个答案:

答案 0 :(得分:2)

您没有引用官方文档,而是用户提供的评论。从XPath查询返回的DOMNodeLists不是&#34;生活&#34;。 removeChild仅从原始文档中删除节点,而不是从DOMNodeList中删除。

相关问题