How to retrieve comments from within an XML Document in PHP

对着背影说爱祢 提交于 2019-12-17 15:01:12

问题


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?


回答1:


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



回答2:


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

//comment()



回答3:


If you are using a SAX event driven-parser, the parser should have an event for comments. For example, when using Expat you would implement a handler and set it using:

void XMLCALL
XML_SetCommentHandler(XML_Parser p,
                      XML_CommentHandler cmnt);



回答4:


Use XMLReader. Comments can be easily detected/found, they are xml elements of type COMMENT. For details see PHP documentation: The XMLReader class

Code example:

$reader = new XMLReader();
$reader->open('filename.xml');
while ($reader->read()){
    if ($reader->nodeType == XMLReader::COMMENT) {
        $comments[] = $reader->readOuterXml();
    }
}

And in array $comments you will have all comments found in XML file.



来源:https://stackoverflow.com/questions/1986764/how-to-retrieve-comments-from-within-an-xml-document-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!