XML to Array

Take the following:


<a>
<b />
<c>
  <c1>aha</c1>
    <c1-1>dsfg</c1-1>
    <c1-2>sdfg</c1-2>
  <c2>fsdg</c2>
</c>
</a>

I’ve been using SimpleXMLElement() to easily access the data in an array LIKE setup. The problem is it is still an object and I have to loop through an assign values to an array myself, and it become problematic for instances such as <c1>.

Any ideas on how I can can easily and simply convert this to an array, no matter the depth of the XLS tree?

There’s a trick with encoding an object to json and then to array using the second parameter set to true in json_decode():


$xmlstr = "<a>
<b />
<c>
  <c1>aha</c1>
    <c1-1>dsfg</c1-1>
    <c1-2>sdfg</c1-2>
  <c2>fsdg</c2>
</c>
</a>";

$xml = new SimpleXMLElement($xmlstr);
$xml_array = json_decode(json_encode($xml), true);
print_r($xml_array);

Ah, beautiful! Thank you!

So it turns out the remote machine that will run this doesn’t have JSON installed, and no possibility of it happening. Any other ideas?

How about a function like this:


function toArray($obj) {
	if(is_object($obj)) {
		$obj = (array) $obj;
	}
	
	if (is_array($obj)) {
		$new = array();
		foreach($obj as $key => $val) {
			$new[$key] = toArray($val);
		}
		
	} else {
		$new = $obj;
	}
	
	return $new;
}


$xmlstr = "<a>
<b />
<c>
  <c1>aha</c1>
    <c1-1>dsfg</c1-1>
    <c1-2>sdfg</c1-2>
  <c2>fsdg</c2>
</c>
</a>";

$xml = new SimpleXMLElement($xmlstr);
$xml_array = toArray($xml);
print_r($xml_array);