Object to array

Often it is useful to change an object into an array, especially when you're parsing xml.

First we'll get some xml:

$ch = curl_init( $xml_url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
$data = curl_exec( $ch );
curl_close( $ch );

You then turn your xml into an object like so:

$xml = new SimpleXmlElement( $data, LIBXML_NOCDATA );

Now you want to loop through your data and find the part of the dataset you're interested in.  Unfortunately $xml is an object and you can't foreach() on it.

The php get_object_vars ($xml); method will convert your object to an array, but it only works one level deep.  You will end up with the dreaded ::__set_state(array( ... ) ) in your array.

A self-iterating function will take care of this:

/**
 * Turn a multi-dimensional object into a multi-dimensional array
 *
 * @param   (object)  $data   - object to convert
 *
 * @return  (array)
 **/
function object_to_array( $data ) 
{
  if( is_object( $data ) ) $data = get_object_vars( $data );
  if( is_array( $data ) ) foreach( $data as $k => $v ) $data[$k] = call_user_func( __FUNCTION__, $v );
  return $data;
}

BTW:

call_user_func( __FUNCTION__, $variable1, $variable2, ... );

is a simple way to build a self-iterating function that will still work if you change the function name.

This also seems to work ( note the TRUE arguement on decode ):

json_decode( json_encode( $xml ), true );

[ Thanks to Aaron E. for json method ]

Top