PHP SimpleXML,在foreach循环期间获取子行
我有一个脚本,它遍历从服务器上保存的文件加载的 SimpleXML 对象。现在,如果在处理 XML 文件时出现问题,我希望脚本报告错误,最好是发生错误的子级行。
XML 示例:
<xml>
<product>
<name>Product one</name>
<price>3.50</price>
</product>
<product>
<name>Product two</name>
<price>42.00</price>
</product>
</xml>
我的脚本像这样处理 XML 文件:
<?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);
?>
现在,我需要知道的是,有没有办法找到 foreach 循环中的当前子级位于哪一行XML 文件?..
我知道 libxml_get_errors()
报告 XML 错误的行,但如果我确定产品有缺陷,我想找出该产品出现在哪一行XML 文件。
我在想,我可以使用孩子的 $key 来询问 simpleXML 在哪里找到了孩子或其他东西,但我不知道如何做。
如果有人有解决方案或建议,请随时分享。
I have a script that goes through a SimpleXML 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这对于 SimpleXML 来说是不可能的。但是,如果您使用普通的 PHP DOM,那么您可以使用
DOMNode:: getLineNo
获取任意 DOM 节点的行号。因此,要么放弃 SimpleXML 并转到完整 DOM,要么在出现错误时在完整 DOM 中解析文档并在那里找到产品节点(及其行号)。
编辑:这是一个 DOM 示例。它超出了我的想象,未经测试,但与您的几乎相同:
有关更多信息,只需检查 PHP DOM 文档
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:
For more information, just check the PHP DOM documentation