Thursday, April 16, 2009

Reading table contents into an XML file

TABLE STRUCTURE

Product
id integer primary key auto_increment,name varchar(50),price decimal(10,2),category_id integer,imagepath varchar(100),updateDay date

PHP CODE

<?php
$con=mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{

mysql_select_db("phpDB",$con);
$query="select * from product";
$result=mysql_query($query,$con);
if (!$file=fopen("report.xml","w+"))
{
echo "Cannot open file";
exit;
}
else
{

$toBeWritten=''."\n\n"."<productinfo>"."\n\n";
while($row=mysql_fetch_array($result))
{
$toBeWritten.="\t<product>"."\n\n".
"\t\t<id>".$row["id"]."</id>"."\n\n".
"\t\t<name>".$row["name"]."</name>"."\n\n".
"\t\t<price>".$row["price"]."</price>"."\n\n".
"\t\t<imagepath>".$row["imagepath"]."</imagepath>"."\n\n".
"\t\t<updateday>".$row["updateDay"]."</updateday>"."\n\n".
"\t\t<category_id>".$row["category_id"]."</category_id>"."\n\n".
"\t</product>"."\n\n";
}
$toBeWritten.="</productinfo>"."\n\n";
if (fwrite($file, $toBeWritten) === FALSE)
{
echo "Cannot write to file";
exit;
}

fclose($file);
$query="commit";
mysql_query($query);
mysql_close($con);
}
}

?>

No comments:

Post a Comment