loading
Please wait while loading...
Back A nice way to output csv with temporary file

In php programming, we always need to output data with csv format, fputcsv is good function to do that. However, it require a file handler which means you must do fopen to open a file write the content to it. But usually we just need to generate the output file for download and don't need to save in server. Today I find a better way to write csv with php memory as shown below.

// output up to 5MB is kept in memory, if it becomes bigger
// it will automatically be written to a temporary file
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');

fputcsv($csv, array('blah','blah'));

rewind($csv);

// put it all in a variable
$output = stream_get_contents($csv);
Comments
comments powered by Disqus