//
you're reading...
Programming

Recursively Converting XML to an Array in PHP

At my job we will soon be collecting environmental data from our own custom made measurement devices. The data loggers will be sending data back to our server via XML over GSM. The XML data can be dynamic, though most transmissions will be uniform in structure. Trying to parse dynamic HTML iteratively would undoubtedly lead to messy code and I knew that there had to be a more elegant solution. The following code recurses over a SimpleXMLElement object and returns a multi-dimensional array:

function xml2array($xmlObj) {
$rtn = array();
foreach((array)$xmlObj as $index => $node )
if(is_object($node) || is_array($node))
$rtn[$index] = xml2array($node);
else
$rtn[$index] = $node;
return $rtn;
}

Additionally I found a nice piece of code on Forrst that will even print it in a tree for you! Can’t ask for me. Hope this helps somebody.

Advertisements

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: