note 75313 deleted from function.simplexml-element-children by danbrown

From: Date: Wed, 16 Sep 2009 15:34:15 +0000
Subject: note 75313 deleted from function.simplexml-element-children by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160636@lists.php.net to get a copy of this message
Note Submitter: aero ---- Here's a slightly modified function that transforms xml data into an associative array with the indices's into the array have the following syntax, parent.child etc. So for <meal> <type>Lunch</type> <time>12:30</time> <menu> <entree>salad</entree> <maincourse>steak</maincourse> </menu> </meal> The array would look like this... array(4) { ["type"]=> string(5) "Lunch" ["time"]=> string(5) "12:30" ["menu.entree"]=> string(5) "salad" ["menu.maincourse"]=> string(5) "steak" } Here's an example <?php $xml = new SimpleXMLElement( '<meal> <type>Lunch</type> <time>12:30</time> <menu> <entree>salad</entree> <maincourse>steak</maincourse> </menu> </meal>'); $vals = array(); RecurseXML($xml,$vals); foreach($vals as $key=>$value) print("{$key} = {$value}<BR>\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; } The output: type = Lunch time = 12:30 menu.entree = salad menu.maincourse = steak ?>

« previous php.notes (#160636) next »