SimpleXML how to get node line number?

I use this in SimpleXML and PHP:

foreach ($xml->children() as $node) {
    echo $node->attributes('namespace')->id;
}

This prints an attribute idfor all nodes (using the namespace).

But now I want to find out the line number that $nodeis in the XML file.

I need a line number because I parse the XML file and return information about possible problems to fix them. So I need to say something like: "You have an error on line X here." I am sure that the XML file will be in a standard format that will have enough line breaks for this to be useful.

+4
source share
1 answer

DOM. DOMNode getLineNo().

DOM

$xml = <<<'XML'
<foo>
  <bar/>
</foo>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

var_dump(
  $xpath->evaluate('//bar[1]')->item(0)->getLineNo()
);

:

int(2)

SimpleXML

SimpleXML DOM, SimpleXMLElement DOMElement.

$element = new SimpleXMLElement($xml);
$node = dom_import_simplexml($element->bar);
var_dump($node->getLineNo());

, , SimpleXML, DOM.

XMLReader

XMLReader , . DOMNode. , libxml2. node , .

$reader = new XMLReader();
$reader->open('data://text/xml;base64,'.base64_encode($xml));

while ($reader->read()) {
  if ($reader->nodeType == XMLReader::ELEMENT && $reader->name== 'bar') {
    var_dump($reader->expand()->getLineNo());
  }
}
+8

All Articles