我使用下面的代码。但是在tmp中创建的文件没有下载。
$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 :(得分: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个参数,在第x行的/path/to/file.php中给出1
将error reporting添加到文件的顶部,这有助于查找错误。
<?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:password@example.com/somefile.txt", "w");
?>
答案 1 :(得分:-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/