PHP convert object to array


Update: I have since revised this function, you can find the newer version in my Revised convertObjectToArray function for PHP article.

I’ve been working these past few days on speeding up the DOMi object, which is one of the major open source tools I’ve been heavily involved in. This object is a blend of DOMDocument, DOMXpath and XSLTProcessor, with a focus on XSLT driven PHP sites and tools for rapidly converting PHP datatypes into XML trees. This object is the core of the Septuro framework that I’m also involved with, and the DOMi object has grown pretty gnarly over the past year.

I’ve managed to slim down the function from 1200 lines to 200 lines, and decrease processing time by about 33%, but one little piece of it is still a challenge – converting an object to array and keep the private and protected properties intact. Right now, the function I have does it just fine, but private and protected properties getting their names kinda messed up, and I’m trying to find the easiest way to correct it, without costing processing time.

At the moment, here is my function:

<?php
function ConvertObjectToArray(&$Object) {
    if(is_object($Object)) {
        $Object = (array)$Object;
        array_walk_recursive($Object, 'ConvertObjectToArray');
    }
    return $Object;
}
?>

The only remaining issue is to get those private and protected properties cleaned up so the names can be transferred into the XML document easily. If you want to check out the current slim version of DOMi, it’s in the Subversion repository, and you can view the file, as it currently stands, through SourceForge. I still need to finish commenting and build __call and __get to automatically pass method/property requests into DOMDocument, DOMXpath and XSLTProcessor so it remains a completely transparent integration of the three objects.

,

  1. No comments yet.
(will not be published)