0

How can I read the first and only comment in PHP:

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

using DOMDOcument object?

$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
gremo
  • 47,186
  • 75
  • 257
  • 421

2 Answers2

4

What about this:

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

Since you probably only want the first one:

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

Source: How to retrieve comments from within an XML Document in PHP

Community
  • 1
  • 1
cutsoy
  • 10,127
  • 4
  • 40
  • 57
  • Fine. Why not //comment()[1]? – gremo Sep 25 '11 at 19:43
  • Since `DOMXPath::query` always returns a list of nodes. Basically, even when you would query `...[1]`, you still got an array-like object (so you still needed to add an additional `$comments = $results[0];` line). **Source**: http://www.php.net/manual/en/domxpath.query.php – cutsoy Sep 25 '11 at 19:44
0

How to get the comments from XML file - look for instructions here:

How to retrieve comments from within an XML Document in PHP

Community
  • 1
  • 1
iluwatar
  • 1,778
  • 1
  • 12
  • 22