开发者

PHP - Simple XML attributes problem

开发者 https://www.devze.com 2023-03-13 00:48 出处:网络
I use PHP and Simple XML. I use a loop that does not work like expected: foreach($item->Image->attributes()->source as $key => $value)

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"]=>
                            str开发者_JAVA技巧ing(2) "41"
                      }
             }
     }

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号