PHP / MySql – Export Data to Excel

A PHP Script to export MySql data to Excel.



$select= "select user_id,email,fname,lname,bdate,fees from user order by fname";
$result = mysql_query($select);
$num_row = mysql_num_rows($result);
$content = “User ID \t”;
$content.= “Email \t”;
$content.= “First Name \t”;
$content.= “Last Name \t”;
$content.= “Birth Date \t”;
$content.= “Fees \n”;

if($num_row > 0)
while($row = mysql_fetch_array($result))
$user_id= (string)$row['user_id']."\t";
$email = $row['email']."\t";
$fname = $row['fname']."\t";
$lname = $row['lname']."\t";
$bdate= substr( str_replace(","," ",$row['bdate']),0,10)."\t";
$fees= (string)str_replace(","," ", number_format($row['fees'], 2, '.', '') )."\n";
$content.= $user_id;
$content.= $email;
$content.= $fname;
$content.= $lname;
$content.= $bdate;
$content.= $fees;
$content = “No Data Found !”;

$tmp_file = "Exported_".date('m_d_Y').".xls";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$tmp_file");
echo $content;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s