Skip to content

Instantly share code, notes, and snippets.

@mtdowling
Created October 12, 2012 06:24
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 mtdowling/3877615 to your computer and use it in GitHub Desktop.
Save mtdowling/3877615 to your computer and use it in GitHub Desktop.
Iterative XML to array conversion
<?php
function iXml2array($xml)
{
$result = array();
$stack = array(array(&$result, &$xml));
do {
$frame = array_pop($stack);
$data =& $frame[0];
$node =& $frame[1];
$namespaces = $node->getNamespaces();
$namespaces[] = null;
foreach ($namespaces as $namespace) {
foreach ($node->attributes($namespace) as $key => $value) {
$data['@attributes'][$key] = (string) $value;
}
}
foreach ($node as $element) {
if (count($element->children())) {
$name = $element->getName();
$data[$name] = array();
$stack[] = array(&$data[$name], &$element);
} else {
$data[$element->getName()] = (string) $element;
}
}
} while ($stack);
return $result;
}
@mtdowling
Copy link
Author

Now that I look at it, this won't work correctly with repeated nodes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment