MySQL Database Results PHP Loop Dynamic XML Node Tutorial
Learn how to access your mysql database and have php render XML structure from the results.
<?php
// PHP file that renders Dynamic XML for MySQL Database result sets
// Script written by Adam Khoury @ www.developphp.com - April 05, 2010
// View the video that is tied to this script for maximum understanding
// -------------------------------------------------------------------
header("Content-Type: text/xml"); // set the content type to xml
// Initialize the xmlOutput variable
$xmlBody = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlBody .= "<XML>";
// Connect to your MySQL database whatever way you like to here
mysql_connect("DB_HostName","DB_UserName","DB_Password") or die (mysql_error());
mysql_select_db("DB_Name") or die ("no database");
// Execute the Query on the database to select items(20 in this example)
$sql = mysql_query("SELECT * FROM my_table ORDER BY date_time DESC LIMIT 0, 20");
while($row = mysql_fetch_array($sql)){
// Set DB variables into local variables for easier use
$id = $row["id"];
$title = $row["title"];
$date_time = strftime("%b %d, %Y", strtotime($row["date_time"]));
$description = $row["description"];
// Start filling the $xmlBody variable with looping content here inside the while loop
// It will loop through 20 items from the database and render into XML format
$xmlBody .= '
<Data>
<DataID>' . $id . '</DataID>
<DataTitle>' . $title . '</DataTitle>
<DataDate>' . $title . '</DataDate>
<DataDescr>' . $description . '</DataDescr>
</Data>';
} // End while loop
mysql_close(); // close the mysql database connection
$xmlBody .= "</XML>";
echo $xmlBody; // output the gallery data as XML file for flash
?>