02 January 2010

export to excel in php

Hi friends
Excel files are great for many things. It might though be a little bit tricky to generate them on the fly with php. Therefor I will guide you exactly how to do it, quick and simple.
Excel is a very useful format for lots of purposes. For example, exporting stats, member lists to hand over to economy department etc. 


<?php

echo "Export Data Using PHP";
echo '
<form action="'. $phpself.'">
';
echo '<input name="submit" type="submit" value="Export" />
</form>
';
?>

}
else
{
$dbc = mysql_connect("localhost","root","");
mysql_select_db("test",$dbc);
$contents="ID,Title,Visit\n";
$user_query = mysql_query('select id,title,visit from wallpaper');
while($row = mysql_fetch_array($user_query))
{
$contents.=$row[0].",";
$contents.=$row[1].",";

$contents.=$row[2]."\n";

}
$contents = strip_tags($contents);                   // remove html and php tags etc.
Header("Content-Disposition: attachment; filename=export.csv");
print $contents;
}
?>





 The output file will be saved as export.csv