我如何阅读PHP中的第一个XML注释?

时间:2011-09-25 19:32:45

标签: php xml dom domdocument

如何阅读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

2 个答案:

答案 0 :(得分:4)

这个怎么样:

$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

答案 1 :(得分:0)

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

How to retrieve comments from within an XML Document in PHP