1

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?

0

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.