PHP XML Generator

Hi,

I’m struggling with something both to resolve and to explain! Here goes…

I’m trying to put together a function that will generate the XML for Ebay API calls. I’ve created a database table that defines each of the node names for one API call with each child node having parent node ID defined in the row.

From that I’ve been able to generate an array for each nodeID so that the array $children_of_item1 for example is an array of [2, 3, 8] - $children_of_item8 is just [10].

The maximum number of children for each node in the table I’m working on is 4 but this could vary in other tables which I’d like to use the same approach on.

The following script is my start on trying to get the XML.



//display the output
//get the top level nodes
echo '<?xml version='.'"'.'1.0'.'"'.' encoding='.'"'.'utf-8'.'"'.'?>';
echo '<'.str_replace('XMLSchema_','',$table_name).'  xmlns='.'"'.'urn:ebay:apis:eBLBaseComponents'.'">'."\
";
$XML_Output='';
$result=@mysql_query("SELECT * FROM $table_name WHERE Node_Level=1 ORDER by Control_ID");
$top_level_items=array();
while ($row = mysql_fetch_array($result)) {
array_push($top_level_items, $row['Control_ID']);
}

$total_in_array=count($top_level_items);
//to parse through the array

for ($array_index=0; $array_index<=$total_in_array; $array_index++) {
$item_to_parse=$top_level_items[$array_index];
$result=@mysql_query("SELECT * FROM $table_name WHERE Control_ID='$item_to_parse'");
while ($row = mysql_fetch_array($result)) {
$node_name=$row['Node_Name'];
$node_value=$row['NodeValueType'];
$XML_Output.='<'.$node_name.'>';
$XML_Output.=$node_value."\
";
$XML_Output.='</'.$node_name.'>'."\
";
}
}
echo $XML_Output;

}
echo '</'.str_replace('XMLSchema_','',$table_name).'>';
}


That gets the top level node names. What I need to do now is find the children of these items, their children, then their children etc, and close each node once all its children have been found then move on to the next top level item. Also I’d like to make sure that nothing gets added to the XML output when no children are found and that the script is completely dynamic i.e. copes whether the number of children in the largest array is 2 or 10.

I’ve just about got there on several occasions over the last day or two but am struggling to successfully close items at the correct point in the loop and to make the loop completely dynamic and was hoping someone might have worked on something similar.

Many thanks in advance

I just hate creating XML output this way. Use DOM instead. It’s very simple.

Thanks for the advice. You may well have confirmed my fears that I have gone off on the wrong tack on this one.