Monday, January 19, 2009

Exporting database table records into an Excel file Using PHP

Hey hero, The below php snippet helps to export a table records into an excel file. Juz copy & paste the below php script as 'export_to_excel.php'. All you need is, Just Point your 'export to excel' link to 'export_to_excel.php' or customize whatever you need. This'll work for you. [Functionality of some lines are commented below]

mysql_connect("localhost","root","") or die(mysql_error());//Database connection
mysql_select_db("jenson") or die(mysql_error());//database name jenson
$time=time();//for unique file name, I've used time() function [Return current Unix timestamp]
header("Content-type: application/vnd.ms-excel");//header setting for Microsoft Excel
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=Report_".$time.".xls");
header("Content-Transfer-Encoding: binary");

$header.="Name\tE-Mail\tAddress\tPhone";
$data=$header."\n\n";
$q=mysql_query("SELECT * FROM details");//Select contents from table details
while($r=mysql_fetch_array($q))
{
$name=stripslashes($r['name']);//table details field 1
$email=stripslashes($r['email']);////table details field 2
$addr=stripslashes($r['address']);//table details field 3
$phone=stripslashes($r['phone']);//table details field 4
$addr=str_replace("\r","",$addr);
$addr=str_replace("\n","",$addr);
$addr = strip_tags($addr,'
'
);

$line .="$name"."\t"."$email"."\t"."$addr"."\t"."$phone"."\t";//4 field values as a record in one line
$line .= "\n";
}

$data .= $line;
echo
$data;// printing each line into each row of an excel file

?>


Juz copy & paste the above php script as 'export_to_excel.php'. Follow the steps mentioned above. Happy coding, Enjoy!

No comments:

Post a Comment