Here's a quick way to dump the nodeValues from SimpleXML into an array using the path to each nodeValue as key. The paths are compatible with e.g. DOMXPath. I use this when I need to update values externally (i.e. in code that doesn't know about the underlying xml). Then I use DOMXPath to find the node containing the original value and update it.
<?php
function XMLToArrayFlat($xml, &$return, $path='', $root=false)
{
$children = array();
if ($xml instanceof SimpleXMLElement) {
$children = $xml->children();
if ($root){ $path .= '/'.$xml->getName();
}
}
if ( count($children) == 0 ){
$return[$path] = (string)$xml;
return;
}
$seen=array();
foreach ($children as $child => $value) {
$childname = ($child instanceof SimpleXMLElement)?$child->getName():$child;
if ( !isset($seen[$childname])){
$seen[$childname]=0;
}
$seen[$childname]++;
XMLToArrayFlat($value, $return, $path.'/'.$child.'['.$seen[$childname].']');
}
}
?>
Use like this:
<?php
$xml = simplexml_load_string(...some xml string...);
$xmlarray = array(); XMLToArrayFlat($xml, $xmlarray, '', true);
?>
You can also pull multiple files in one array:
<?php
foreach($files as $file){
$xml = simplexml_load_file($file);
XMLToArrayFlat($xml, $xmlarray, $file.':', true);
}
?>
The respective filename/path is thus prefixed to each key.