dpl57372 2018-08-01 15:10
浏览 17
已采纳

如何遍历从xml加载到php的数组

I have an XML file as follows:

<Main>
<SubMain>
  <First>10570</First>
  <Time>07:33:51</Time>
  <Result>500</Result>
  <Taken>8:14</Taken>
  <Results>
    <int>100</int>
    <int>100</int>
    <int>85</int>
    <int>100</int>
    <int>100</int>
    <int>100</int>
    <int>100</int>
  </Results>
</SubMain>
</Main>

That I am loading from a file into PHP using simplexml_load_file:

   $xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
    foreach($xml->children() as $child)
   {
        echo $child->getName() . ": " . $child->First . $child->Time . $child->Taken ."<br>";

    }

When I load in the Results row I am not getting any values returned, how do I step into this sub-array? Sorry if it's a daft question but has had me stumped today!

Edit: Removed the typo since it does not exist in the code, also to be clear the First, Time, Result etc are returning the expected values, it is the sub array (Results) I can not seem to pull data from.

  • 写回答

1条回答 默认 最新

  • douxuzui4590 2018-08-01 15:35
    关注

    All values returned when using SimpleXML are SimpleXMLElement objects, which can be cast to native types (e.g. var_dump($xml->SubMain->First);). It also implements Traversable so it can be used in foreach loops.

    To get the <int> values, you will need to loop over the children of <Result>:

    foreach ($xml->SubMain->Results->children() as $result) {
        // $result is a SimpleXMLElement object, needs casting
        var_dump(intval($result));
    }
    

    You can also cast directly to an array, but note that you will have an array of strings:

    $ints = (array) $xml->SubMain->Results->int;
    var_dump($ints); // actually strings
    

    So you could do something like this:

    $ints = array_map('intval', (array) $xml->SubMain->Results->int);
    var_dump($ints);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失