Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download csv file

Tags:

php

we have a button when we click on that button all data come into csv file and download this csv file. csv file create but download code not working

$fp = fopen("file\customer-list.csv", "w");
fileName = "file\customer-list.csv";
$filePath = "file\customer-list.csv";
$fsize = filesize("file\customer-list.csv");

if(($_POST['csv_download_list']) == "cm")
{
    fwrite($fp, $csv);
    fclose($fp); 
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Disposition: attachment; filename=\"$fileName\"");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Content-Length: ' . filesize($filePath));
    ob_clean();
    flush();
    $file = @fopen($filePath,"rb");
    if ($file) {
        while(!feof($file)) {
            print(fread($file, 1024*8));
            flush();
        }
    @fclose($file);
}
exit;
like image 277
Preeti Bisht Avatar asked Nov 30 '22 02:11

Preeti Bisht


2 Answers

Use this snippet should do what you are trying to do.

<?php

    $file = 'sample.csv'; //path to the file on disk

    if (file_exists($file)) {

        //set appropriate headers
        header('Content-Description: File Transfer');
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();

        //read the file from disk and output the content.
        readfile($file);
        exit;
    }
?>
like image 80
Saurabh Kumar Avatar answered Dec 18 '22 21:12

Saurabh Kumar


You don't need to save the file to the disk, just echo the csv content after setting the appropriate header. Try the code below, it will be much simpler

$fileName = 'customer-list.csv';

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $fileName);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

echo $csv;
exit;
like image 43
xdazz Avatar answered Dec 18 '22 22:12

xdazz