Skip to content

Instantly share code, notes, and snippets.

@njones
Created June 2, 2010 18:00
Show Gist options
  • Save njones/422740 to your computer and use it in GitHub Desktop.
Save njones/422740 to your computer and use it in GitHub Desktop.
/**
* Breaks XML down into a nice array... it flattens namespace prefixes without a schema.
*
* @author Nika Jones
*
* @copyright 2010 Appcelerator Inc.
*
* Licensed under the terms of the Apache Public License
* http://www.apache.org/licenses/LICENSE-2.0
*
*/
function xml2array($xml)
{
static $n = 0;
$_r = array();
$l = 0;
if(is_string($xml)) { $xml = simplexml_load_string($xml); }
foreach($xml->xpath("*") as $child)
{
$child_name = implode(":", array_filter(array(dom_import_simplexml($child)->prefix, $child->getName())));
if(count($child->xpath("*")) > 0)
{
$n++;
$_r[$child_name][] = xml2array($child);
$n--;
}
else
{
$_r[$child_name] = count($child->xpath("@*")) > 0 ? array($l=>array("@text"=>(string)$child)) : (string)$child;
}
foreach($child->xpath("@*") as $attr)
{
if($attr->getName() == "") { continue; }
$attr_name = implode(":", array_filter(array(dom_import_simplexml($attr)->prefix, $attr->getName())));
$_r[$child_name][$l]['@attributes'][$attr_name] = (string)$attr;
}
// because we'll have the "@attributes" key.. so we need to add to the $l.. otherwise, no need to increment
if(count($child->xpath("@*")) > 0)
{
$l++;
}
}
return $_r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment