[英]Make a CSV file Downloadable
I use the below code. 我使用下面的代码。 But the file created in tmp is not downloading .
但是在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);
}
This answer is as per your original post without marking your edited post as an " edit ". 该答案是按照您的原始帖子,而不将您编辑的帖子标记为“ edit ”。
The problem is that fopen()
requires 2 parameters. 问题是
fopen()
需要2个参数。
As per the manual: 按照手册:
<?php
$handle = fopen("c:\\folder\\resource.txt", "r");
?>
So this line: 所以这行:
$error = fopen(/tmp/error.csv);
should read as (which is missing quotes and since you want to write to the file, w
) 应该读为(缺少引号,并且由于您要写入文件
w
)
$error = fopen('/tmp/error.csv', 'w');
You may need to adjust your path, something to the effect of: 您可能需要调整路径,以达到以下目的:
$error = fopen('/var/user/you/tmp/error.csv', 'w');
or 要么
$error = fopen('/var/user/you/public_html/tmp/error.csv', 'w');
If you had error reporting on, it would have signaled something similar to this: 如果您有错误报告,则可能表示类似以下内容:
Warning: fopen() expects at least 2 parameters, 1 given in /path/to/file.php on line x
警告:fopen()至少需要2个参数,第1行的/path/to/file.php中给出1个参数
Add error reporting to the top of your file(s) which will help find errors. 将错误报告添加到文件顶部,这将有助于发现错误。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Sidenote: Error reporting should only be done in staging, and never production. 旁注:错误报告仅应在登台进行,而不应在生产过程中进行。
More examples from the manual: 手册中的更多示例:
<?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");
?>
try this code 试试这个代码
// 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);
taken from this link http://code.stephenmorley.org/php/creating-downloadable-csv-files/ 取自此链接http://code.stephenmorley.org/php/creating-downloadable-csv-files/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.