note 75313 added to function.simplexml-element-children
| From: | aero at osu1 dot php dot net | Date: | Wed, 23 May 2007 15:35:08 +0000 |
| Subject: | note 75313 added to function.simplexml-element-children | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-126846@lists.php.net to get a copy of this message | ||
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
?>
----
Server IP: 64.71.164.2
Probable Submitter: 66.240.57.253
----
Manual Page -- http://www.php.net/manual/en/function.simplexml-element-children.php
Edit -- https://master.php.net/note/edit/75313
Del: integrated -- https://master.php.net/note/delete/75313/integrated
Del: useless -- https://master.php.net/note/delete/75313/useless
Del: bad code -- https://master.php.net/note/delete/75313/bad+code
Del: spam -- https://master.php.net/note/delete/75313/spam
Del: non-english -- https://master.php.net/note/delete/75313/non-english
Del: in docs -- https://master.php.net/note/delete/75313/in+docs
Del: other reasons-- https://master.php.net/note/delete/75313
Reject -- https://master.php.net/note/reject/75313
Search -- https://master.php.net/manage/user-notes.php