tags:

views:

285

answers:

2

I have a program which reads an XML file using the DOM functions:

$doc = new DOMDocument('1.0');
$doc->load("myFile.xml");

As I traverse the nodes in this document, is there a way to tell which line of the input file the node was defined on?

For example:

1: <!-- myFile.xml -->
2: <foobar>
3:     <foo>FOO</foo>
4:     <bar>BAR</bar>
5: </foobar>

and the PHP:

$xp = new DOMXPath($doc);
$bars = $xp->query("//bar");
$myBar = $bars[0];
echo "The first <bar> element is on line " . performMagicHere(); // 4
+1  A: 

You can't really do this with PHP's DOM class. DOM Level 3 added support for this, but we don't have DOM level 3 support in PHP yet.

TML
+1  A: 

$element->getLineNo() will return the line number of the opening tag. Note: for opening tags that span more than one line, it will return the end of the opening tag. It doesn't seem to work for DOMText nodes though (returns 0).

http://us3.php.net/manual/en/domnode.getlineno.php

scotts
Excellent! Note that this is for PHP 5.3.0+ only.
nickf