Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing certain properties of a SimpleXMLElement Object

Tags:

php

xml

simplexml

When I print_r() the SimpleXMLElement Object referenced by variable $xmlObject, I see the following structure:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [uri] => /example
        )

    [result] => SimpleXMLElement Object
        (
            [message] => Record(s) added successfully
            [recorddetail] => Array
                (
                    [0] => SimpleXMLElement Object
                    ...
                )
        )
)

Notice how the $xmlObject->result->message property looks like it is just a string. However, if I do print_r($xmlObject->result->message), I get the following:

SimpleXMLElement Object
(
    [0] => Record(s) added successfully
)

So at this point I'm confused. Why is $xmlObject->result->message being identified as an instance of SimpleXMLElement Object in this case, when the result of printing the full $xmlObject doesn't suggest this?

And how do I actually access this value? I've tried $xmlObject->result->message[0], but it just prints out the same thing (i.e. the last code snippet I posted).

like image 819
maxedison Avatar asked Mar 13 '12 20:03

maxedison


1 Answers

The representation you get when using print_r or var_dump on a SimpleXMLElement has very little to do with how it is structured internally. For instance there is no property @attributes you could access with $element['@attributes']['uri'] either. You just do $element['uri']

This is simply the way it is. SimpleXmlElement objects behave different. Make sure you read the examples in the PHP Manual before using SimpleXml:

  • http://php.net/manual/en/simplexml.examples-basic.php

To understand the implementation it in detail, you'd have to look at the source code:

  • http://lxr.php.net/opengrok/xref/PHP_TRUNK/ext/simplexml/simplexml.c

To print $xmlObject->result->message you just do echo $xmlObject->result->message. That will autocast the SimpleXmlElement to string.

like image 186
Gordon Avatar answered Sep 24 '22 04:09

Gordon