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 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色