<?php
//-----------------------------------------------------------------------------------
//Convert a nested PHP array into a standard XML output
//-----------------------------------------------------------------------------------

header("Content-type: text/xml"); 

$data = array( array("student_id"=>123, "fname"=>"Barbara", "lname"=>"Burns",  "sex"=>"F"),
               array("student_id"=>124, "fname"=>"David",   "lname"=>"Runyon", "sex"=>"M"),
               array("student_id"=>125, "fname"=>"Patrick", "lname"=>"Stack",  "sex"=>"M"),
             );    

$xml_data = new SimpleXMLElement('<?xml version="1.0"?><root></root>');	   //create a new XML object

array_to_xml($data, $xml_data);						   //convert 

//$text = $xml_data;              			#without the tags

$text = $xml_data->asXML();              		#with the tags

$text = preg_replace('/</', '<', $text);		#convert all '<' to < to print on web

print "<textarea style='width:500%; height:500%'>";             //so XML displays properly              
print "$text";
print "</textarea>";


//-----------------------------------------------------------------------------------
//Convert a nested PHP array into a standard XML output
//-----------------------------------------------------------------------------------
function array_to_xml($data, &$xml_data) 
{
    foreach($data as $key => $value) 
    {
        if(is_numeric($key))
            $key = 'item'.$key;                        //dealing with <0>..</0> issues

        if(is_array($value)) 
        {
            $subnode = $xml_data->addChild($key);
            array_to_xml($value, $subnode);
        } 
        else 
            $xml_data->addChild("$key",htmlspecialchars("$value"));
    }
}

?>