我有一個腳本,通過從服務器上保存的文件加載的SimpleXML對象。現在,如果在處理XML文件時出現問題,我希望腳本報告錯誤,最好是發生錯誤的子項的行。PHP SimpleXML,在foreach循環中獲取子行
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它發現那個孩子什麼的,但我不知道如何。
如果任何人有解決方案或建議,請隨時分享。
感謝您的答覆,您可以提供怎樣我的腳本示例以上可以使用DOM?因爲我不知道如何使用DOM來讀取XML。 –
@Kristoffer:這很簡單。我已經更新了我的答案。 –
謝謝,它的工作原理。我將在稍後爲我的腳本實現DOM。 –