【问题标题】:PHP - Simple XML attributes problemPHP - 简单的 XML 属性问题
【发布时间】:2011-06-14 08:21:02
【问题描述】:

我使用 PHP 和 Simple XML。

我使用的循环不像预期的那样工作:

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

在 foreach 中,我试图告诉我想要获取属性中列出的图像的“来源”。

上面的$item 是在foreach($xml_content->Section->Item as $item {} 上面的代码周围循环创建的,(如果您需要知道它来自哪里)

我的对象如下所示:

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"
                      }
             }
     }

我的帖子开头的循环有什么问题?

【问题讨论】:

    标签: php arrays object attributes simplexml


    【解决方案1】:

    您正在尝试迭代字符串,而不是数组

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

    要迭代 Image 元素的所有属性,请使用

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

    如果只想输出源属性的值,不要迭代而是使用简写

    echo $item->Image['source']
    

    查看demoSimpleXml Basic Usage Examples in the PHP Manual

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      相关资源
      最近更新 更多