How to retrieve comments from within an XML Document in PHP

SimpleXML cannot handle comments, but the DOM extension can. Here’s how you can extract all the comments. You just have to adapt the XPath expression to target the node you want.

$doc = new DOMDocument;
$doc->loadXML(
    '<doc>
        <node><!-- First node --></node>
        <node><!-- Second node --></node>
    </doc>'
);

$xpath = new DOMXPath($doc);

foreach ($xpath->query('//comment()') as $comment)
{
    var_dump($comment->textContent);
}

Leave a Comment