php-> mySQL to XML format

I recently implemented some software that required XML format text for input. The customers database was a mySQL database. So I scoured the web for an easy solution. I found a few that had errors and/or did not work. After examining these and reading the PHP manual a dozen times I hit upon a solution that works. You may use this code for what ever purposes.


< ?php
// Connect to the database
$link= mysql_connect("localhost", "mySQLUserName", "mySQLPassWord");
if (! $link ){
$dberror= mysql_error();
print $dberror;
return false;
}
//connect to database
mysql_select_db('databaseName', $link);
if (! mysql_select_db('databaseName', $link)){
$dberror= mysql_error();
print $dberror;
return false;
}

//Create your query to pull the info you want in your xml file.
$query = "SELECT DISTINCT item, COUNT(*) FROM `tableName` GROUP BY 'item' ORDER BY NULL ";
$result = mysql_query($query) or die("error");
$num= mysql_num_rows($result);

if ($num != 0){

//Create a table called data.xml - Set its ChMOD to 775 in order to write to it....
//Open the data.xml table and write...

$file = fopen("data.xml", "w");
// Add the top text of the xml file...
$_xml = " \n”;
$_xml .= “ \n”;

//use the query data to populate the xml file
while ($row = mysql_fetch_array($result)) {
$_xml .= “\n “;
$_xml .= ““.$row[1].” \n “;
$_xml .= $row[0].”\n
\n”; }

//yields value

//end of the file closing the database tag
$_xml .= ““;
// do the write thing
fwrite($file, $_xml);
//close the xml file
fclose($file);
// optional note to show data.xml was written or redirect.
echo “xml written”;

}
// free the query result.
mysql_free_result($result);

?>

Good luck with your application.

One Response to “php-> mySQL to XML format”

  1. Jeff A Says:

    Ewww, complicated stuff. Stop it, your scaring me!