Skip to content

Instantly share code, notes, and snippets.

@mmollick
Last active May 17, 2017 19:38
Show Gist options
  • Select an option

  • Save mmollick/fc8a17a788b03a5bc83fedee4f35eed9 to your computer and use it in GitHub Desktop.

Select an option

Save mmollick/fc8a17a788b03a5bc83fedee4f35eed9 to your computer and use it in GitHub Desktop.
Propper XML to Array
/**
* Creates an associative array from XML. XML elements with like named siblings
* become numeric indexed arrays. Attributes are not retained.
*
* Input XML:
* <Root>
* <RequestId>12345</RequestId>
* <Users>
* <User>
* <Name>Ted</Name>
* </User>
* <User>
* <Name>John</Name>
* </User>
* </Users>
* </Root>
*
* Output Array:
* [
* "Root" => [
* "RequestId" => 12345,
* "Users" => [
* ["Name" => "Ted"]
* ["Name" => "John"]
* ]
* ]
* ]
*
* @param SimpleXMLElement $xml
* @return array
*/
function xmlIterator(SimpleXMLElement $xml)
{
// Awis & AWIS namespaces
$xml->registerXPathNamespace('aws',
'http://alexa.amazonaws.com/doc/2005-10-05/');
$xml->registerXPathNamespace('awis',
'http://awis.amazonaws.com/doc/2005-07-11');
$arr = [];
// Check for children
$xpath = $xml->xpath('*');
if (count($xpath) > 0) {
$redundant = false;
foreach ($xpath as $node) {
// Check if key exists already
if(isset($arr[$node->getName()])) {
// The node name keying becomes redundant when working with arrays
$redundant = true;
// Convert to numeric array
if(!is_array($arr[$node->getName()]) || !isset($arr[$node->getName()][0])) {
$tmp = $arr[$node->getName()];
$arr[$node->getName()] = [];
$arr[$node->getName()][] = $tmp;
$arr[$node->getName()][] = xmlIterator($node);
}
// Add to existing numeric array
else if(is_array($arr[$node->getName()])) {
$arr[$node->getName()][] = xmlIterator($node);
}
} else {
$arr[$node->getName()] = xmlIterator($node);
}
}
// Check if this a redundantly nested array
if($redundant && isset($node)) {
$arr = $arr[$node->getName()];
}
} else {
$arr = trim((string) $xml);
}
return $arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment