如何从PHP中的XML文档中检索注释 [英] How to retrieve comments from within an XML Document in PHP

查看:124
本文介绍了如何从PHP中的XML文档中检索注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PHP提取XML文档中特定节点下面的所有注释。我试过SimpleXML和DOMDocument方法,但我不断得到空白的输出。

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?

推荐答案

SimpleXML不能处理注释,但是DOM扩展可以。这里是如何提取所有的意见。你只需要修改XPath表达式来定位你想要的节点。

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

这篇关于如何从PHP中的XML文档中检索注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆