【问题标题】:How can i read the first XML comment in PHP?如何阅读 PHP 中的第一个 XML 注释?
【发布时间】:2011-11-24 18:30:27
【问题描述】:

如何阅读 PHP 中的第一条也是唯一一条评论:

<?xml version="1.0" encoding="UTF-8"?>
<!-- read this -->
<root>
</root>

使用 DOMDOcument 对象?

$xml = new DOMDocument();

$libxml_error = 'Il file %s non risulta ben formato (%s).';

// Per evitare i warning nel caso di xml non ben formato occorre sopprimere
// gli errori
if (!@$xml -> load($xml_file_path)) $error = sprintf($libxml_error,
    $xml_file_path, libxml_get_last_error()->message);

// Read the fist comment in xml file

【问题讨论】:

    标签: php xml dom domdocument


    【解决方案1】:

    这个呢:

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

    因为你可能只想要第一个:

    $xpath = new DOMXPath($xml);
    $results = $xpath->query('//comment()');
    $comment = $results[0];
    var_dump($comment);
    

    来源How to retrieve comments from within an XML Document in PHP

    【讨论】:

    • 很好。为什么不 //comment()[1]?
    • 因为DOMXPath::query 总是返回一个节点列表。基本上,即使您查询...[1],您仍然会得到一个类似数组的对象(因此您仍然需要添加额外的$comments = $results[0]; 行)。 来源php.net/manual/en/domxpath.query.php
    【解决方案2】:

    如何从 XML 文件中获取 cmets - 在此处查找说明:

    How to retrieve comments from within an XML Document in PHP

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 2010-10-17
      • 1970-01-01
      相关资源
      最近更新 更多