скачать файл csv

у нас есть кнопка, когда мы нажимаем эту кнопку, все данные поступают в файл csv и загружают этот файл csv. Создание csv-файла, но загрузка кода не работает

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

Использовать этот фрагмент должен делать то, что вы пытаетесь сделать.

 <?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; } ?> 

Вам не нужно сохранять файл на диск, просто эхо-содержимое csv после установки соответствующего заголовка. Попробуйте код ниже, он будет намного проще

 $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; 
 Try... function download($file) { if (!file_exists($file)) { return false; } header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename="' . basename($file) . '"'); header('Content-Length: ' . filesize($file)); readfile($file); exit(); } $file = "file.csv"; download($file);