views:

74

answers:

1

From what I can tell, a SimpleXMLElement is just an array of other SimpleXMLElements, plus some regular array values if there wasn't a tag nested in another tag.

I have a SimpleXMLElement in a variable $data, and var_dump($data) gives me this:

object(SimpleXMLElement)#1 (33) {
  ["buyer-accepts-marketing"]=>
  string(4) "true"
...
...

but calling var_dump($data->buyer-accepts-marketing) gives me an error, and var_dump($data["buyer-accepts-marketing"]) gives me NULL. Calling var_dump($data->shipping-address->children()) gives me an error.

going like this:

foreach($data as $item) {
    var_dump($item);
}

gives a whole bunch of SimpleXMLElement objects, but oddly enough, no strings or ints.

What am I missing here? I want to take specific portions of it and pass them to a function, so for example, I don't have to go

$data->billing-address->postal-code;

...

$data->shipping-address->postal-code;

...

and can just go

address($data->billing-address);
address($data->shipping-address);

etc.

+5  A: 

SimpleXMLElement is not just an array. To access child elements, you must use object notation ($a->b) and to access attributes you must use array notation ($a['b']).

Problem is, with object notation, valid tag names can be illegal PHP code.

You need to do this:

$data->{'buyer-accepts-marketing'};

Note that this returns a SimpleXMLElement! The reason for this is that it can contain either just text, more child elements, or both. The output of var_dump() is very misleading for SimpleXMLElements. If you want to the text content of a single <buyer-accepts-marketing> tag, you have to do this:

(string)$data->{'buyer-accepts-marketing'};

Of course it is also perfectly legal to do this:

(int)$data->{'buyer-accepts-marketing'};

The reason this appears to work in some cases (such as echoing a SimpleXMLElement) is that the type conversions are implicit and automatic. You can't echo an object, so PHP automatically converts it to a string.

I have a love/hate relationship with SimpleXML. It makes things very easy only after you understand how complex the actual API is.

Read up on the so-called "basic" examples to get a good handle on it.

Mike
yes! victory! Thank you so much!
Carson Myers