@motyar

I'm Motyar, an entrepreneur and API developer from India

Creating value through Programming

DigitalOcean Cloud hosting for developers
20GB SSD, 512MB RAM - only $5 per month

Jul 7, 2012

Php Object to Array

Want to share a simple but very useful php function. It helped me in many projects while parsing XML. We got simple Object by loading XML with simplexml_load_string or simplexml_load_file. This function converts a complex object to array.

Its more easy to parse and access and array than a object
Here is the function


//Function returns array by a SimpleXmlObject
function object2array($object){
    $return = NULL;
      
    if(is_array($object))
    {
        foreach($object as $key => $value)
            $return[$key] = object2array($value);
    }
    else
    {
        $var = get_object_vars($object);
          
        if($var)
        {
            foreach($var as $key => $value)
                $return[$key] = ($key && !$value) ? NULL : object2array($value);
        }
        else return $object;
    }

    return $return;
}


Labels: ,


By :