RSS
 

XML => UID Associative Array

25 May

I found myself in need of ‘flattening’ an XML tree. Basically, I needed a means of storing XML elements in to database to search for results at a latter time. The following PHP code transforms the XML tree into an associative array with the following schema

$phparray['parent.child'][$i] = $value

Where $i would indicate the sibling number. The *combination* of the latter index and the sibling number conveniently constitute a primary key :)

Okay here’s the code…

$xml = new SimpleXMLElement('

Lunch

salad
chips
steak

‘);
$vals = array();

RecurseXML($xml,$vals);

foreach($vals as $key=>$value)
foreach($value as $k=>$v)
print(“{$key}[{$k}] = {$v}
\n”);

function RecurseXML($xml,&$vals,$parent=”")
{
$child_count = 0;
foreach($xml as $key=>$value)
{
$child_count++;
$k = ($parent == “”) ? (string)$key : $parent . “.” . (string)$key;
if(RecurseXML($value,$vals,$k) == 0) // no childern, aka “leaf node”
$vals[$k][] = (string)$value;
}
return $child_count;
}

/* OUTPUT
type[0] = Lunch
time[0] = 12:30
menu.entree[0] = salad
menu.entree[1] = chips
menu.maincourse[0] = steak
*/

?>

 
No Comments

Posted in RIA

 

Leave a Reply

 

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word