Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Turn a simplexml document in simple array key/values
*/
function simplexml_to_array($xml) {
$output = array();
foreach($xml->children() as $tagname => $value) { // recurse the child
$child = simplexml_to_array($value); // if it's not an array, then it was empty, thus a value/string
if( count($child) == 0 ) $child = (string)$value;
foreach( $value->attributes() as $ak => $av ) { // add the childs attributes as if they where children
if( !is_array( $child ) ) { // if the child is not an array, transform it into one
$child = array( "name" => $child );
}
$child[$ak] = (string)$av;
}
if (!in_array($tagname,array_keys($output))) { // if the $tagname is already in our children list, we need to transform it into an array, else we add it as a value
$output[$tagname] = $child;
} elseif (@in_array(0,@array_keys($output[$tagname]))) {
$output[$tagname][] = $child;
} else {
$output[$tagname] = array($output[$tagname]);
$output[$tagname][] = $child;
}
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.