PHP can be used to create dynamic XML files that get data from your MySql database.
Things to consider with the code below:
- There should be no spaces or open lines before “
- All values between ‘[]’ brackets need to be replaced by your own settings.
- The three header lines will make sure your browser reads the page as XML and stops it from Caching the XML. By not caching the page you can use your XML data to dynamically update pages with Ajax every few seconds. (Without caching it will display out of date data till the cache expires)
- All data from your database needs to be surrounded by the CDATA tags. This makes sure that the data from the DB is presented correctly on your page.
<?php header("Content-type: text/xml"); // indicates that its XML and not html header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past $con = mysql_connect("localhost","[username]","[password]"); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("[table]", $con); if (!$db_selected) { die ("Can't use test_db : " . mysql_error()); } $sql = "SELECT * from [YourTable]"; $result = mysql_query($sql,$con); $xml_output = "<!--?<span class="hiddenSpellError" pre=""-->xml version=\"1.0\" encoding=\"utf-8\" ?> "; $xml_output .= "<root>"; while($row = mysql_fetch_array($result)) { $xml_output .= " <input>"; $xml_output .= " [FieldName]"; $xml_output .= " <!--[<span class="hiddenSpellError" pre=""-->CDATA[" . $row['[FieldName]'] . "]]>"; $xml_output .= " </input>"; } $xml_output .= "</root>"; echo $xml_output; mysql_close($con); ?>
Cool again!