列出 SimpleXml 对象

我正在尝试使用 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 ResultItem

70 ResultItem

- Status

- 43 ResultItem

- Status

- 72 ResultItem

- 100 ResultItem

这是我期望的:


42 ResultItem

- Status

- 43 ResultItem

70 ResultItem

- Status

- 72 ResultItem

- 100 ResultItem

错误在哪里?


我如何区分 foreach 循环中的两个“Record->ResultData->ResultItem”,因为它们都有一个“ElementID”属性和两个不同的值?


RISEBY
浏览 109回答 1
1回答

肥皂起泡泡

根据提供的 xml 结构,您可以执行以下操作:foreach ($xml->Record->ResultData as $element) {&nbsp;&nbsp; foreach ($element as $key => $val) {&nbsp; &nbsp; echo $val['ElementID'].' '.$key.PHP_EOL;&nbsp; &nbsp; // iterate over children of current element `$val`&nbsp; &nbsp; foreach ($val as $key1 => $element1) {&nbsp;&nbsp; &nbsp; &nbsp; if ($key1 === 'Status') {&nbsp; &nbsp; &nbsp; &nbsp; echo '- '.$key1.PHP_EOL;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; } elseif ($key1 === 'ResultItem') {&nbsp; &nbsp; &nbsp; &nbsp; echo '- '.$element1['ElementID'].' '.$key1.PHP_EOL;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP