Monthly Archives

March 2011

Converting XML to Associative Array in PHP

Sometimes there are situations where I have had code that is expecting an Associative Array with its corresponding values to deal with. However, as can often stand the case when propagating over to XML, sometimes its not possible (or digitally healthy) to convert everything all at once and I end up in a situation where I have all my data in single layer XML objects but need to interact with it on an associate array level.

So, as a quick to fix I wrote this small function entitled xml2AssArray() to deal with the children of a single layer XML object and turn it into an array with the children’s names used as the key-names of the array.

function xml2AssArray($xmlobj)
{
    $assarray = array(); // Initialize the Array
    // Loop through the XML object's children
    foreach ($xmlobj->children() as $child)
    {
        // Assign the childs name as the key for the next entry while assigning the value itself as well
        $assarray[$child->getName()] = $child;
    }
    return $assarray; // Return the new Array
}

Let’s take this XML object (called $myxml which we create using SimpleXML) for example:

<?xml version="1.0"?>
<Lead>
    <ID>1213</ID>
    <SSN>123450000</SSN>
    <FullName>Israel Smith</FullName>
</Lead>

When we run it through our new function, the array that is returned, is now an associate array:

> $myarray = xml2AssArray($myxml);
> echo $myarray['FullName'];
Israel Smith
>

Huzzah!