Sunday, February 1, 2015

Converting SimpleXMLElement returned object to associative PHP array

This trick is pretty cool, putting SimpleXMLElement output through json encode and decode actually yield a perfect PHP associative array. Nice!


<?php
$xml = '<blah>123</blah>';

$simpleXML_obj = new SimpleXMLElement($xml);
// echo __LINE__.':simpleXML_obj: '.print_r($simpleXML_obj, true)."\n";

if(!empty($simpleXML_obj)){
	$json = json_encode($simpleXML_obj);
	if(!empty($json)){
		$arr = json_decode($json, true);
		if(!empty($arr)){
			// Got nice associative array!
			echo __LINE__.':arr: '.print_r($arr, true)."\n";
		}
	}
}
?>

No comments:

Post a Comment