Skip to content

Instantly share code, notes, and snippets.

@SchizoDuckie
Created August 3, 2013 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SchizoDuckie/6145817 to your computer and use it in GitHub Desktop.
Save SchizoDuckie/6145817 to your computer and use it in GitHub Desktop.
/**
* 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