Hi,
I am converting an adjacency table to a xml with this code (coming from phpfreaks, thank you Barand!)
<?php
$data = array(
1 => 0,
2 => 1,
3 => 1,
4 => 2,
5 => 3,
6 => 5
);
echo "<?xml version='1.0' encoding='iso-8859-1'?>\n";
echo "<tree id='0'>\n";
tree(0);
echo "</tree>\n";
function tree ($parent, $level=0)
{
global $data;
$children = array_keys($data, $parent);
if ($children)
foreach ($children as $kid)
{
$indent = str_repeat("\t", $level+1);
echo "$indent<item text='$kid' id='$kid'>\n";
tree($kid, $level+1);
echo "$indent</item>\n";
}
}
?>
Returning
<?xml version='1.0' encoding='iso-8859-1'?>
<tree id='0'>
<item text='1' id='1'>
<item text='2' id='2'>
<item text='4' id='4'>
</item>
</item>
<item text='3' id='3'>
<item text='5' id='5'>
<item text='6' id='6'>
</item>
</item>
</item>
</item>
</tree>
Which is inappropriately formatted for my purpose. I would need:
<?xml version='1.0' encoding='iso-8859-1'?>
<tree id='0'>
<item text='1' id='1'>
<item text='2' id='2'>
<item text='4' id='4'/>
</item>
<item text='3' id='3'>
<item text='5' id='5'>
<item text='6' id='6'/>
</item>
</item>
</item>
</tree>
All nodes with children should end with </item>, leafs without end with />).
I included an else-statement, after the foreach, but that obviously only doubles the leafs.
else
{
$leaf = $parent;
$indent = str_repeat("\t", $level+1);
echo "$indent<item text='$leaf' id='$leaf'/>\n";
}
Including further if-statements, left me with a completely screwed xml.
Now I run out of ideas how to check for leafs/children and handle them appropriately. Any help ist appreciated!