你不能在 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);
}
?>