Reputation: 561
After much googling and tinkering around a bit i managed to export the table to .csv file but now i'd like to initiate the download via the browser instead of automatically storing in a folder.
Here's my code:
<?php
$server = 'localhost';
$user = 'root';
$pass = 'pass';
$db = 'test';
$db = mysqli_connect($server, $user, $pass, $db);
mysqli_set_charset($db, "utf8");
$filename = 'uploads/'.strtotime('now').'.csv';
$fp = fopen($filename,"w");
$query = "SELECT id,product,status,created,summary FROM product_table";
$result = mysqli_query($db,$query) or die( "My query ($query) generated an error: ".mysql_error());
$row = mysqli_fetch_assoc($result);
$seperator = "";
$comma = "";
foreach ($row as $name => $value){
$seperator.= $comma. ''.str_replace('','""',$name);
$comma=",";
}
$seperator .= "\n";
echo $seperator;
//putting the heading into the csv file
fputs($fp,$seperator);
mysqli_data_seek($result,0);
while ($row = mysqli_fetch_assoc($result)){
$seperator = "";
$comma = "";
foreach ($row as $name => $value){
if (strcmp($name,'summary') == 0){
$value = str_replace( array( "\r" , "\n", "\r\n", "\n\r" ) ,'' , $value);
$value = str_replace('</b><br>','',$value);
$value = str_replace('<b>','',$value);
$value = str_replace('<br>','',$value);
$value = str_replace('<br />','',$value);
}
$seperator.= $comma. ''.str_replace('','""',$value);
$comma=",";
}
$seperator .= "\n";
//putting the heading into the csv file
fputs($fp,$seperator);
}
fclose($fp);
?>
Running the above script stores the .csv file in the folder uploads. What changes to do i need to make to enable browser download so that users can run the script and download the .csv file via the browser? thanks!
EDIT: Furthermore what modifications would i have to make if wanted to disable saving to the folder and only enable user/browser downloads? thanks.
Upvotes: 0
Views: 5739
Reputation: 1360
i think following two lines enough to force browser to auto download csv file
header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="dishes.csv"');
where filename -- give name name csv file name
Upvotes: 0
Reputation: 5351
Try with this:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=your_file.csv');
header('Pragma: no-cache');
readfile($filename);
Upvotes: 4
Reputation: 915
surely the table titles appear twice because this line appears twice in the code in different places:
//putting the heading into the csv file
fputs($fp,$seperator);
Upvotes: 1