How to retrieve comments from within an XML Document in PHP

后端 未结 4 1731
走了就别回头了
走了就别回头了 2020-12-04 03:04

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 out

4条回答
  •  死守一世寂寞
    2020-12-04 03:59

    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(
        '
            
            
        '
    );
    
    $xpath = new DOMXPath($doc);
    
    foreach ($xpath->query('//comment()') as $comment)
    {
        var_dump($comment->textContent);
    }
    

提交回复
热议问题