2014-11-05 60 views
0

我使用下面的代碼。但在tmp中創建的文件不會下載。製作CSV文件可下載

$error = fopen(/tmp/error.csv); 
    $write[] = "hello"; 
    $dest_file_path="/tmp/error.csv"; 
     $dest_file_name="error.csv"; 
     if(!empty($write)) 
     { 
      $flag = FALSE; 
      fputcsv($error,$write,";"); 
      fclose($error); 
      header("Content-Transfer-Encoding: Binary"); 
      header("Content-length: ".filesize($dest_file_path)); 
      header('Content-Type: text/csv'); 
      header('Content-Disposition: attachment; filename="'.$dest_file_name.'"'); 
      readfile($dest_file_path); 
     } 
+0

你給的權限? – 2014-11-05 05:42:36

+0

是的。它已擁有777個權限。 – Torrezzzz 2014-11-05 05:45:44

+0

請勿使用我的答案編輯/覆蓋您的問題,而不將其標記爲編輯。我因爲這個原因而陷入低調。我正在回滾。您可以在編輯之後進行編輯,並將其標記爲原始文章完整保留的編輯。如果在我的回答中不起作用,請問我。 – 2014-11-05 06:13:13

回答

-1

試試這個代碼

// output headers so that the file is downloaded rather than displayed 
header('Content-Type: text/csv; charset=utf-8'); 
header('Content-Disposition: attachment; filename=data.csv'); 

// create a file pointer connected to the output stream 
$output = fopen('php://output', 'w'); 

// output the column headings 
fputcsv($output, array('Column 1', 'Column 2', 'Column 3')); 

// fetch the data 
mysql_connect('localhost', 'username', 'password'); 
mysql_select_db('database'); 
$rows = mysql_query('SELECT field1,field2,field3 FROM table'); 

// loop over the rows, outputting them 
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row); 

從這個鏈接http://code.stephenmorley.org/php/creating-downloadable-csv-files/

1

這個答案是每your original post採取無標記your edited post爲 「編輯」。


問題是fopen()需要2個參數。

按手冊:

<?php 
$handle = fopen("c:\\folder\\resource.txt", "r"); 
?> 

所以這行:

$error = fopen(/tmp/error.csv); 

應爲已讀(這是缺少報價,因爲要寫入文件,w

$error = fopen('/tmp/error.csv', 'w'); 

您可能需要調整自己的路徑,其效果如下:

$error = fopen('/var/user/you/tmp/error.csv', 'w'); 

$error = fopen('/var/user/you/public_html/tmp/error.csv', 'w'); 

如果你在錯誤報告上,就已經暗示與此類似:

警告:fopen()函數預計至少給予2個參數,1 /path/to/file.php線X

添加error reporting到您的文件(S)的頂部,他將lp找到錯誤。

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 

旁註:錯誤報告只應在分期完成,並且從不生產。從手動


更多的例子:

<?php 
$handle = fopen("/home/rasmus/file.txt", "r"); 
$handle = fopen("/home/rasmus/file.gif", "wb"); 
$handle = fopen("http://www.example.com/", "r"); 
$handle = fopen("ftp://user:[email protected]/somefile.txt", "w"); 
?>