2012-06-01 262 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);