Monday, May 16, 2011

Php Code - Generate XML from database

Php code to generate XML from database.

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

mysql_connect('hostname','user','password');
mysql_select_db('database_name');
$query = mysql_query("select * from table_name");

?>
<?php   

  $domtree = new DOMDocument('1.0', 'UTF-8');
  $xmlRoot = $domtree->createElement("xml");
  $xmlRoot = $domtree->appendChild($xmlRoot);
  $currentTrack = $domtree->createElement("itemset");
  $currentTrack = $xmlRoot->appendChild($currentTrack); 

 while($row = mysql_fetch_assoc($query))
    {
        $currentTrack1 = $currentTrack->appendChild($domtree->createElement("item"));
        foreach($row as $index=>$val)
            {
                $currentTrack1->appendChild($domtree->createElement($index,$val));

            }
    } 

 echo $domtree->saveXML();
?>

1 comment: