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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀