PHP - 简单的XML属性问题

Jen*_*ell 1 php arrays attributes object simplexml

我使用PHP和Simple XML.

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

foreach($item->Image->attributes()->source as $key => $value)
{
    echo $value;
}
Run Code Online (Sandbox Code Playgroud)

在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"
                      }
             }
     }
Run Code Online (Sandbox Code Playgroud)

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

Gor*_*don 5

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

$item->Image->attributes()->source
Run Code Online (Sandbox Code Playgroud)

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

foreach ($item->Image->attributes() as $attributeName => $attributeValue) {
Run Code Online (Sandbox Code Playgroud)

如果您只想输出source属性的值,请不要迭代但使用简写

echo $item->Image['source']
Run Code Online (Sandbox Code Playgroud)

请参阅PHP 演示文稿中的此演示SimpleXml基本用法示例