tags:

views:

102

answers:

4

How would I get to the name variable given the object. $obj->@attributes['name']; would obviously not work.

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [name] => Address
        )

    [value] => Address
)
A: 

I believe it's just $obj['name'].

See their basic usage doc for more info.

Justin Johnson
+3  A: 

What about $obj['name'] ?

For instance, if you take this portion of code :

$str = <<<XML
<root>
    <a name="test">
        glop
    </a>
</root>
XML;

$xml = simplexml_load_string($str);

And these :

var_dump($xml->a);

Will get you :

object(SimpleXMLElement)[2]
  public '@attributes' => 
    array
      'name' => string 'test' (length=4)
  string '
        glop
    ' (length=18)

And

var_dump($xml->a['name']);

Will get you :

object(SimpleXMLElement)[4]
  string 'test' (length=4)

And casting this to a string :

var_dump((string)$xml->a['name']);

Finally gets you what you want :

string 'test' (length=4)

ie, you just use array-access to get the values of attributes.

Pascal MARTIN
ooh thanks. worked perfectly
wnoveno
Really should I cast it to string? OMG!
pihentagy
+1  A: 

You're asking the wrong question. Don't ask people how to do things your way, ask them how to do them right.

Describe what you really want to do, not how you're trying to do it.

Josh Davis
It sounds like what he really wants to do is get the name variable out of the attributes. How would he do that with a `SimpleXMLElement`?
Dominic Rodger
ok. but really It's just I haven't encountered @attributes before.
wnoveno
+1  A: 

For a SimpleXMLElement, you can access attributes using array access syntax

$obj['name']

Alternatively, you could type

$obj->attributes()->name
Richard Nguyen