我正在尝试使用 php SimpleXml 列出一个 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错误在哪里?我如何区分 foreach 循环中的两个“Record->ResultData->ResultItem”,因为它们都有一个“ElementID”属性和两个不同的值?
1 回答
肥皂起泡泡
TA贡献1829条经验 获得超6个赞
根据提供的 xml 结构,您可以执行以下操作:
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 关注
- 108 浏览
添加回答
举报
0/150
提交
取消