douyakan8924 2013-09-10 11:42
浏览 36
已采纳

循环遍历simplexml_load_file结果

I'm trying to use simplexml_load_file to get the info in my xml file into variables. The structure of the xml file is:

<root>
    <item>
        <sku></sku>
        <weight></weight>
        <Price></Price>
        <media>
            <images></images>
            <images></images>
            <images></images>
        </media>
        <short_description>
            <![CDATA[]]>
        </short_description>
        <description>
            <![CDATA[]]>
        </description>
    </item>
    <item>
        <sku></sku>
        <weight></weight>
        <Price></Price>
        <media>
            <images></images>
            <images></images>
            <images></images>
        </media>
        <short_description>
            <![CDATA[]]>
        </short_description>
        <description>
            <![CDATA[]]>
        </description>
    </item>
</root>

Here's what I've done so far, but it's only getting the first image for each item not all the images. Apart from that it seems to be working fine.

$xml_url="accessories.xml";
$xml = simplexml_load_file($xml_url);
foreach($xml->item as $_item){
    echo $_item->sku . " - ";
    echo $_item->weight . " - ";
    echo $_item->Price . " <br/>";
    //echo $_item->short_description . " <br/><br/>";
    foreach($_item->media as $_media){
        echo $_media->images . "<br/>";
    }
}

My php and xml skills are pretty limited so I'd appreciate any help you can give.
Thanks

  • 写回答

2条回答 默认 最新

  • doudou0111 2013-09-10 11:51
    关注

    You should use like following foreach

    foreach($_item->media->images as $_media){
        echo $_media . "<br/>";
    }
    

    You'll see because of why with below dumped media data:

    var_dump($_item->media);
    
    object(SimpleXMLElement)[5]
      public 'images' => 
        array (size=3)
          0 => string '1' (length=1)
          1 => string '2' (length=1)
          2 => string '3' (length=1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?