Home » Php » php – How to export a dynamically generated temporary csv file?

php – How to export a dynamically generated temporary csv file?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I would like to generate a csv file with data, that I get by querying a database. The browser then should prompt the user to download the file. By problem is, that the readfile function needs a filename and not a handle, but I can’t find a function to get the filename of this temporary file.
I guess there are better ways to do this, but I can’t find them.

$handle = tmpfile();
fputcsv($handle, array('year', 'month', 'product', 'count'));
header('Content-Type: application/csv');
header('Content-Disposition:attachment;filename=LS_export');
echo readfile($handle);
fclose($handle);
exit();
How to&Answers:

You are looking for rewind to reset the file pointer to the start of the file, followed by fpassthru to output all the contents of the file.

rewind($handle);
fpassthru($handle);

Another solution is to use tempnam to generate a unique file which is not removed when closed. Do not forget to remove it manually when you are done with it.

$name = tempnam('/tmp', 'csv');
$handle = fopen($name, 'w');
...
fclose($handle);
readfile($name);
unlink($name);

Answer:

Use

$tmpfname = tempnam("/", "");
$handle = fopen($tmpfname, "w");
...
fclose($handle);

And you have the filename too.

Answer:

from mysql

SELECT id, name, email INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\’
LINES TERMINATED BY '\n'
FROM users WHERE 1

and delete it on demand

redefine separators and other param as you need