How to export dynamically created temporary csv file?

I would like to create a csv file with the data that I get by querying the database. Then the browser should ask the user to download the file. The problem is that the readfile function requires a file name, not a descriptor, but I cannot find a function to get the file name of this temporary file. I think there are better ways to do this, but I cannot 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(); 
+7
source share
3 answers

You look for rewind to reset the file pointer to the beginning of the file, and then fpassthru to display the entire contents of the file.

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

Another solution is to use tempnam to create a unique file that is not deleted when it is closed. Remember to remove it manually when you are done with it.

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

Use

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

And you also have a file name.

+2
source

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

override delimiters and other parameters as needed

0
source

All Articles