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

Viewed 697

I have some HTML that contains this:

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

I'm doing str_replace() on the contents of these elements:

$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);
}

That should replace any spaces with an "X".

But it results in this error:

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

It works if there's only one nested div:

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

Why does this happen, and how can I get it working?

1 Answers

Try changing

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

to

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

Edit per comments:

Assuming there's a space in the outer element (i.e., its "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);
}
Related