PHP: How to Convert stdClass Object to Array

PHPIn my latest project, I am doing SOAP calls to a SOAP service that uses WSSE security headers.

If you happen to use PHP’s SoapClient class, then you may notice that when your methods return data, they are returning stdClass Objects.

Objects aren’t as easy to work with as arrays, so you may want to convert the returned object into a multidimensional array.

Here’s a good function to go about doing that (courtesy of JR)

<?php
	function objectToArray($d) {
		if (is_object($d)) {
			// Gets the properties of the given object
			// with get_object_vars function
			$d = get_object_vars($d);
		}
		if (is_array($d)) {
			/*
			* Return array converted to object
			* Using __FUNCTION__ (Magic constant)
			* for recursive call
			*/
			return array_map(__FUNCTION__, $d);
		}
		else {
			// Return array
			return $d;
		}
	}
?>

It sure is a lot easier to deal with that data now!

Leave a Reply

Your email address will not be published.