Looping through a SimpleXML object, or turning the whole thing into an array


I’m trying to work out how to iterate though a returned SimpleXML object.

I’m using a toolkit called Tarzan AWS, which connects to Amazon Web Services (SimpleDB, S3, EC2, etc). I’m specifically using SimpleDB.

I can put data into the Amazon SimpleDB service, and I can get it back. I just don’t know how to handle the SimpleXML object that is returned.

The Tarzan AWS documentation says this:

Look at the response to navigate through the headers and body of the response. Note that this is an object, not an array, and that the body is a SimpleXML object.

Here’s a sample of the returned SimpleXML object:

So what code do I need to get through each of the object items? I’d like to loop through each of them and handle it like a returned mySQL query. For example, I can query SimpleDB and then loop though the SimpleXML so I can display the results on the page.

Alternatively, how do you turn the whole shebang into an array?

I’m new to SimpleXML, so I apologise if my questions aren’t specific enough.


You can use the SimpleXML object (or its properties) in a foreach loop. If you want to loop through all the ‘records’ something like this can be used to access and display the data:

Note that $Item will be a SimpleXML object, as is $Attribute, so they need to be referenced as objects, not arrays.

While the example code above is looping through the arrays in the SimpleXML object ($SimpleXML->body->QueryWithAttributesResult->Item), you can also loop through a SimpleXML object (say $SimpleXML->body->QueryWithAttributesResult->Item[0]), and that would give you each of the object’s properties.

Each child element of a SimpleXML object is an XML entity. If the XML entity (tag) is not unique, then the element is simply an array of SimpleXML objects representing each entity.

If you want, this should create a more common row/fields array from your SimpleXML object (or get you close):

Leave a Reply