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"?>
    <FullName>Israel Smith</FullName>

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


Belisarius Smith consults as a software engineer, cloud engineer, and security advisor. He has a BSBA in Security Management, a Masters of Software Engineering from Penn State, and is doing graduate studies in Psychology. When he isn't traveling, mountain climbing, or reading, he spends his spare time on personal side projects and studies.

Leave a Reply