我正在嘗試使用 php SimpleXml 列出一個(gè) XML 文件:<Record> <TestData> <Status>Passed</Status> <Date Year="2018" Month="1" Day="25" Hour="11" Min="41" Sec="24"/> </TestData> <ResultData> <ResultItem ElementID="42"> <Status>Passed</Status> <ResultItem ElementID="43"> <Status>Passed</Status> </ResultItem> </ResultItem> <ResultItem ElementID="70"> <Status>Passed</Status> <ResultItem ElementID="72" Version="1"> <Status>Passed</Status> </ResultItem> <ResultItem ElementID="100" Version="1"> <Status>Passed</Status> </ResultItem> </ResultItem> </ResultData></Record>這是我的 php 代碼: $xml = simplexml_load_file ('20000.xml');foreach ($xml->Record->ResultData as $element) { foreach ($element as $key => $val) { echo $val['ElementID'].' '.$key.'</br>'; foreach ($xml->Record->ResultData->ResultItem as $element1) { foreach ($element1 as $key1 => $val1) { echo '- '.$val1['ElementID'].' '.$key1.'</br>'; } } }} 這就是我得到的:42 ResultItem- Status- 43 ResultItem- Status- 72 ResultItem- 100 ResultItem70 ResultItem- Status- 43 ResultItem- Status- 72 ResultItem- 100 ResultItem這是我期望的:42 ResultItem- Status- 43 ResultItem70 ResultItem- Status- 72 ResultItem- 100 ResultItem錯(cuò)誤在哪里?我如何區(qū)分 foreach 循環(huán)中的兩個(gè)“Record->ResultData->ResultItem”,因?yàn)樗鼈兌加幸粋€(gè)“ElementID”屬性和兩個(gè)不同的值?
1 回答

肥皂起泡泡
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
根據(jù)提供的 xml 結(jié)構(gòu),您可以執(zhí)行以下操作:
foreach ($xml->Record->ResultData as $element) {
foreach ($element as $key => $val) {
echo $val['ElementID'].' '.$key.PHP_EOL;
// iterate over children of current element `$val`
foreach ($val as $key1 => $element1) {
if ($key1 === 'Status') {
echo '- '.$key1.PHP_EOL;
} elseif ($key1 === 'ResultItem') {
echo '- '.$element1['ElementID'].' '.$key1.PHP_EOL;
}
}
}
}
- 1 回答
- 0 關(guān)注
- 134 瀏覽
添加回答
舉報(bào)
0/150
提交
取消