PHP: "Couldn't fetch DOMElement. Node no longer exists in" 使用 DOMXpath

PHP: "Couldn't fetch DOMElement. Node no longer exists in" using DOMXpath

我有一些 HTML 包含这个:

<div class="test">
  Outer
  <div class="test">Inner 1</div>
  <div class="test">Inner 2</div>
</div>

我正在str_replace()处理这些元素的内容:

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);

foreach($xpath->query("//div[@class='test']") as $node) {
    $node->nodeValue = str_replace(" ", "X", $node->nodeValue);
}

应该用 "X" 替换任何空格。

但它导致了这个错误:

Warning: Couldn't fetch DOMElement. Node no longer exists in /path/to/my/file.php on line 63

如果只有一个嵌套则有效 div:

<div class="test">
  Outer
  <div class="test">Inner 1</div>
</div>

为什么会发生这种情况,我该如何让它工作?

尝试更改

foreach($xpath->query("//div[@class='test']") as $node) 

foreach($xpath->query('//div[@class="test"]//div[@class="test"]') as $node)

根据评论编辑:

假设在外部元素中有一个 space(即它的“Outer 1:”):

<?php
$string = <<<XML
<div class="test">
  Outer 1
  <div class="test">Inner 1</div>
  <div class="test">Inner 2</div>
</div>
XML;
$dom = new DOMDocument();
$dom->loadHTML($string);
$xpath = new DOMXpath($dom);

foreach($xpath->query('//div[@class="test"]//text()') as $node) {
   $nnode = trim($node->nodeValue);

   echo $nnode  = str_replace(" ", "X", $nnode);
}