Search code examples
phpxpathdomdocument

How to get the next HTML element after a comment by XPath?


I get the comments in an HTML document by XPath

$xpath = new DOMXPath($doc);

$comments = $xpath->query('//comment()');

foreach ($comments as $comment)
{
    echo $comment->nodeValue.PHP_EOL;
}

How can I get the next HTML element in this loop from $comment?


Solution

  • You could alter your XPath expression to use the following-sibling axis and say pick up the first node after the comment...

    $comments = $xpath->query('//comment()/following-sibling::*[1]');
    

    If you need the comment and the next node, you can first get the comment and then use XPath relative to that comment to fetch the following node...

    $comments = $xpath->query('//comment()');
    foreach ($comments as $comment)
    {
        echo $comment->nodeValue.PHP_EOL;
        $next = $xpath->query("following-sibling::*[1]", $comment)[0];
        echo $next->nodeValue.PHP_EOL;
    }