Converting SimpleXML Objects into Arrays

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

PHP’s simple XML is sometimes counter intuitive. Whilst it is acknowledged to be more simple than its predecessors, the “simple” name might be pushing things a bit.

One thing that keeps cropping up when working with SimpleXML is the way that it lets you work with its objects as if they were arrays. That sometimes makes you feel like you are working with an array - and therefore makes things confusing when they display particularly non array like behaviour.

Sometimes the simplest thing to do here is to turn the object into a real array.

Check out this function:

function sx_array($obj){
	$arr = (array)$obj;
	if(empty($arr)){
		$arr = "";
	} else {
		foreach($arr as $key=>$value){
			if(!is_scalar($value)){
				$arr[$key] = sx_array($value);
			}
		}
	}
	return $arr;
}

For example if you are working with an xml element that may or may not contain attributes, converting to an array first will allow you to figure this out.

For example

$file_index_xml = new SimpleXMLElement($local_full_index, NULL, TRUE);
foreach($file_index_xml->xpath("/interface/files.index/file") as $file){
	$arr = sx_array($file->attributes());
	if($arr['@attributes']['Value']){
		//do something
	}
}

Tags: edmondscommerce