alkhader
alkhader

Reputation: 998

Export MySQL data to CSV file using PHP

I have a small problem with exporting MySQL data to CSV file, it print out the data correctly from the table but at the end of the csv file it prints also the html page code!

Below is my code

$file="billing";
     $i=0;
     $values = mysql_query("SELECT * FROM billing");
     $rown=0;
     while( $row = mysql_fetch_assoc($values)){
     if($rown++==0)
       $csv_output.=implode(";",array_keys($row))."\n";
       $csv_output.=implode(";",array_values($row))."\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: text/csv");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
}

Output:

billing_id;customer_id;user_id;trans_id;transfer;balance;created;text;credit;sender_id      
257;29;;-1;0;500000;1330930434;Payment;500000;      
258;29;;-1;200000;300000;1330930465;Sender ID reg.;0;jkjjhh     
284;32;;-1;0;1000000;1331708884;Payment;1000000;        
285;32;564;268;-120;999880;1331709106;SMS send;;        
286;32;;-1;0;1000000;1331709234;Payment;120;        
287;32;564;269;0;1000000;1331723634;SMS send;;


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">       
    <html xmlns="http://www.w3.org/1999/xhtml">     
    <head>      
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />       
    <title>Client Manger</title>        
    <link rel="stylesheet" href="/style/my-style.css">      
    <form action='./' method='post'>        
    <input type="hidden" name="action" value="billing" class="text">        
    <input type="hidden" name="customer_id" value=""  />

What could be the reason?

Thanks for all.

Upvotes: 0

Views: 1836

Answers (1)

cwallenpoole
cwallenpoole

Reputation: 81988

You need to have exit; or die(); after the print $csv_output; Otherwise the rest of the page (outside of that close } (which I suspect is the end of an if statement)) will print (and therefore be included in the CSV).


Just a thought: it might be a better idea to have two PHP files to handle this: one which outputs the CSV, the other which outputs the form. Not only allow you to avoid using die/exit or very long else statements it will also result in cleaner code overall.


As another thought, you are better off using do...while any time you want to have something happen the first time (and only the first time). So this might be a better option:

$row = mysql_fetch_assoc($values);
$csv_output.=implode(";",array_keys($row))."\n";
do
{
    // notice how there is no flag needed!
    // also, you don't need to call 'array_values' when imploding
    $csv_output.=implode(";",$row)."\n";
}while( $row = mysql_fetch_assoc($values));

Upvotes: 1

Related Questions