Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve comments from within an XML Document in PHP

I want to extract all comments below a specific node within an XML document, using PHP. I have tried both the SimpleXML and DOMDocument methods, but I keep getting blank outputs. Is there a way to retrieve comments from within a document without having to resort to Regex?

like image 403
Olaseni Avatar asked Nov 20 '25 09:11

Olaseni


2 Answers

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);
}
like image 126
Josh Davis Avatar answered Nov 22 '25 00:11

Josh Davis


Do you have access to an XPath API ? XPath allows you to find comments using (e.g.)

//comment()
like image 34
Brian Agnew Avatar answered Nov 22 '25 00:11

Brian Agnew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!