Alon
Alon

Reputation: 3906

php objects, how to access a simplexmlelement

I have the following object:

object(SimpleXMLElement)#337 (1) { [0]=> string(4) "1001" }

But I can't seem to access it using [0] or even not using foreach($value as $obj=>$objvalue)

What am I doing wrong?

Upvotes: 1

Views: 123

Answers (3)

Sven van Zoelen
Sven van Zoelen

Reputation: 7229

By looking into the SimpleXMLElement manual I found this example (the example XML file is on the top of the page of the link):

$movies = new SimpleXMLElement($xmlstr);

/* For each <character> node, we echo a separate <name>. */
foreach ($movies->movie->characters->character as $character) {
   echo $character->name, ' played by ', $character->actor, PHP_EOL;
}

And I found this function to transform the XML object to an array, maybe that's easier to use?:

    function toArray($xml) { //$xml is of type SimpleXMLElement 
        $array = json_decode(json_encode($xml), TRUE);

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( empty($value) ) $array[$key] = NULL;
            elseif ( is_array($value) ) $array[$key] = toArray($value);
        }

        return $array;
    }

Upvotes: 0

WolvDev
WolvDev

Reputation: 3226

Try to use

$objectarray = get_object_vars(object(SimpleXMLElement));

Upvotes: 0

xdazz
xdazz

Reputation: 160833

SimpleXMLElement implements Traversable, which means you could use foreach to loop it.

Upvotes: 1

Related Questions