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

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

报告相同问题?

悬赏问题

  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用