drvjlec1767 2013-02-13 19:55
浏览 23
已采纳

动态检索xml数据

I am working with simplexml to retrieve data.

The data I am having trouble with looks like this:

SimpleXMLElement Object
(
    [listing_pics_array] => SimpleXMLElement Object
        (
            [pic0] => http://imagepath.com_1.jpg
            [pic1] => http://imagepath.com_2.jpg
            [pic2] => http://imagepath.com_3.jpg
            [pic3] => http://imagepath.com_4.jpg
            [pic4] => http://imagepath.com_5.jpg
            [pic5] => http://imagepath.com_6.jpg
            [pic6] => http://imagepath.com_7.jpg
        )
)

I am able to retrieve the url like this: (string)$listing->listing_pics_array->pic0[0]

I want to dynamically loop over the listing_pic_array because I have no idea how many pics will be returned.

I want to do something like this:

foreach ($listing->listing_pics_array as $key => $value) {
    echo '<img src="'.$value .'" alt="" />';
}

but I am getting nothing returned.

Thanks.

  • 写回答

1条回答 默认 最新

  • duanjiao5261 2013-02-13 20:17
    关注

    Try casting the SimpleXMLElement into an Array. This one works fine for me:

    $sXml = <<<XML
    <?xml version='1.0'?>
    <root>
      <listing_pics_array>
        <pic0>pic0 foo</pic0>
        <pic1>pic1 bar</pic1>
      </listing_pics_array>
    </root>
    XML;
    
    $oXml = simplexml_load_string($sXml);
    foreach ((array)$oXml->listing_pics_array as $sCurrentValue) {
      echo $sCurrentValue . PHP_EOL;
    }
    

    Yielded

    pic0 foo
    pic1 bar
    

    HTH

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题