简体   繁体   中英

php export to csv user/browser download

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.

Try with this:

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=your_file.csv');
header('Pragma: no-cache');
readfile($filename);

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM