note 51008 modified in function.simplexml-element-children by danbrown
| From: | danbrown@php.net | Date: | Wed, 16 Sep 2009 15:35:40 +0000 |
| Subject: | note 51008 modified in function.simplexml-element-children by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-160641@lists.php.net to get a copy of this message | ||
The example below shows the basic use of depth-first recursion to span the xml tree.
This is coded for the command line, and it prints out the original sentance above and then the copy
cat sentence it creates itself for comparison, which as you will see; this example is slightly off
from, I'll leave it upto you to resolve this issue.
All in all I personaly think xml and recursion go hand in hand, so if you don't understand
recursion but know xml and want to use php to manipulate xml you will need to learn about recursion
at some point.
<?php
$xml = simplexml_load_string(
'<person>
<child role="son">
<child role="daughter"/>
</child>
<child role="daughter">
<child role="son">
<child role="son"/>
</child>
</child>
</person>');
function recurse($child)
{
foreach($child->children() as $children) {
echo ' who begot a '.$children['role'];
recurse($children);
}
return;
}
foreach($xml->children() as $children) {
echo 'The person begot a '.$children['role'];
recurse($children, 0);
echo '; ';
}
echo "\n";
echo 'The person begot a son who begot a daughter; The person begot a daughter who begot a son;
and that son begot a son'."\n";
?>
--was--
The example below shows the basic use of depth-first recursion to span the xml tree.
This is coded for the command line, and it prints out the original sentance above and then the copy
cat sentence it creates itself for comparison, which as you will see; this example is slightly off
from, I'll leave it upto you to resolve this issue.
All in all I personaly think xml and recursion go hand in hand, so if you don't understand
recursion but know xml and want to use php to manipulate xml you will need to learn about recursion
at some point.
<?
$xml = simplexml_load_string(
'<person>
<child role="son">
<child role="daughter"/>
</child>
<child role="daughter">
<child role="son">
<child role="son"/>
</child>
</child>
</person>');
function recurse($child)
{
foreach($child->children() as $children) {
echo ' who begot a '.$children['role'];
recurse($children);
}
return;
}
foreach($xml->children() as $children) {
echo 'The person begot a '.$children['role'];
recurse($children, 0);
echo '; ';
}
echo "\n";
echo 'The person begot a son who begot a daughter; The person begot a daughter who begot a son;
and that son begot a son'."\n";
?>
http://php.net/manual/en/function.simplexml-element-children.php