PHP SimpleXML, get line of child during foreach loop
I have a script that goes through a Sim开发者_运维知识库pleXML object loaded from a file that is saved on the server. Now, if something's wrong while i process the XML file, i want the script to report the error, and preferably the line of the child where the error occurred.
An example of XML:
<xml>
<product>
<name>Product one</name>
<price>3.50</price>
</product>
<product>
<name>Product two</name>
<price>42.00</price>
</product>
</xml>
My script processes the XML file like this:
<?php
$log = 'Error log'.PHP_EOL;
$xml = simplexml_load_file('file.xml');
foreach($xml->'product' as $key->$val) {
if(everything_is($okay)) {
//process product
}
else {
$log .= 'There was an error with the product on line '.$childLine.PHP_EOL;
}
}
file_put_contents('log.txt',$log);
?>
Now, the thing i need to know here is, is there a way to find which line the current child in the foreach loop is on in the XML file?..
I know that libxml_get_errors()
reports the line of the XML-errors, but if i determine that a product has flaws, i want to find out what line the product appears on in the XML file.
I was thinking something where i use the $key of the child to ask simpleXML where it found that child or something, but i don't know how.
If anyone have a solution or a suggestion, feel free to share it.
That's not possible with SimpleXML. But, if you use the normal PHP DOM then you can use DOMNode::getLineNo
to get the line number of any DOM node.
So, either drop SimpleXML and go for the full DOM, or, parse your document in the full DOM when there is an error and find the product node (and it's line number) there.
Edit: Here's a DOM example. It's off the top of my head, so untested, but pretty much identical to yours:
$xml = new DOMDocument();
$xml->load('file.xml');
foreach ($xml->getElementsByTagName('product') as $product) {
if (everything_is_okay($product)) {
// do something
} else {
$log .= 'Bad product on line ' . $product->getLineNo();
}
}
file_put_contents('log.txt',$log);
For more information, just check the PHP DOM documentation
精彩评论