Fetch all rows from mysql database and write the output in xml file

// Connect to the database
$mcm_db = mysql_connect("localhost", "root", "");
mysql_select_db("sample", $mcm_db);

// Issue the query
$mcm_query = sprintf("SELECT date, text FROM xmltb" );
$mcm_result = mysql_query($mcm_query, $mcm_db);

// Format the query results as XML
if (mysql_num_rows($mcm_result) > 0) {
// Assemble the XML code
$xml ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";
$xml.="<firsttag>\r\n";
while (list($date, $text) = mysql_fetch_array($mcm_result)) {
$formatted_date = $date;
$formatted_time = $text;
$xml.= sprintf(" <second date=\"%s\" text=\"%s\">\r\n",
$formatted_date, $formatted_time);
$xml.= " </second>\r\n";
}
$xml.="</firsttag>";

// Write the XML code to the file mcm_results.xml
$file= fopen("mcm_results.xml", "w");
fwrite($file, $xml);
fclose($file);

echo "The XML document has been written - <a href=\"mcm_results.xml\">
view the XML code.</a>";
} else {
echo "Sorry, no matching records found.";
}
// Close the database
mysql_close($mcm_db);

Tags: 
X