1

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

2 Answers 2

2

$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).

https://www.php.net/manual/en/domnode.getlineno.php

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.