donglang9880 2011-06-14 08:21
浏览 18
已采纳

PHP - 简单的XML属性问题

I use PHP and Simple XML.

I use a loop that does not work like expected:

foreach($item->Image->attributes()->source as $key => $value)
{
    echo $value;
}

In the foreach I try to tell that I want to get the "source" of the image which is listed in the attributes.

$item above is created with a loop around my code above foreach($xml_content->Section->Item as $item {}, (if you need to know where it came from)

My object looks like this:

object(SimpleXMLElement)#36 (4) {
    ["Text"]=>
        string(15) "Vinbergs socken"
    ["Description"]=>
        string(73) "Vinbergs socken ingick i Faurås härad och ligger i Falkenbergs kommun.
    "
    ["Url"]=>
        string(44) "http://sv.wikipedia.org/wiki/Vinbergs_socken"
    ["Image"]=>
         object(SimpleXMLElement)#38 (1) {
             ["@attributes"]=>
                  array(3) {
                      ["source"]=>
                            string(113) "http://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Faur%C3%A5s_Vinberg.svg/50px-Faur%C3%A5s_Vinberg.svg.png"
                      ["width"]=>
                          string(2) "50"
                      ["height"]=>
                            string(2) "41"
                      }
             }
     }

What is wrong with my loop in the beginning of my post?

  • 写回答

1条回答 默认 最新

  • douxing6434 2011-06-14 08:27
    关注

    Your are trying to iterate a string, not an array

    $item->Image->attributes()->source
    

    To iterate all the attributes of the Image element, use

    foreach ($item->Image->attributes() as $attributeName => $attributeValue) {
    

    If you just want to output the value of the source attribute, do not iterate but use the shorthand

    echo $item->Image['source']
    

    See this demo and the SimpleXml Basic Usage Examples in the PHP Manual

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

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来