您不能在 foreach 循环中迭代时从 DOMNodeList 中移除 DOMNode。例如...
<?php
$domNodeList = $domDocument->getElementsByTagname('p');
foreach ( $domNodeList as $domElement ) {
// ...对 $domElement 进行操作...
$domElement->parentNode->removeChild($domElement);
}
?>
... 将看似让 foreach 的内部迭代器变得混乱,结果会很奇怪。不过,创建一个要移除的项目的队列似乎可以解决问题。例如...
<?php
$domNodeList = $domDocument->getElementsByTagname('p');
$domElemsToRemove = array();
foreach ( $domNodeList as $domElement ) {
// ...对 $domElement 进行操作...
$domElemsToRemove[] = $domElement;
}
foreach( $domElemsToRemove as $domElement ){
$domElement->parentNode->removeChild($domElement);
}
?>