2012-06-01 212 views
3

我们有一个按钮,当我们点击那个按钮时,所有数据进入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; 
+0

为什么你在你的文件中这么多的变数卢金周围。反正..我认为这个http://stackoverflow.com/questions/1487774/generating-csv-file-and-then-forcing-the-file-to-download应该可以解决你的问题。 – Saurabh

+0

您也可以选择退出.. http://php.net/manual/en/function.readfile.php – Saurabh

+0

如果有可接受的答案,请将其标记为答案。 –

回答

3

你并不需要将文件保存到磁盘,正好呼应设置适当的头后的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; 
16

使用此代码段应该做你正在尝试做的。

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

真的很有帮助,谢谢! –

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