fputcsv () is an incredible little function, so I won't give it up.
Instead, I suggest you play with the built-in PHP I / O Wrappers
You can do this, for example, to "stream" your CSV data line by line (given the different output buffers, but that's a different story):
<?php header('Content-type: text/csv; charset=UTF-8'); header('Content-disposition: attachment; filename=report.csv'); $fp = fopen('php://output','w'); foreach($arrays as $array) fputcsv($fp, $array);
This works fine, but if something goes wrong, your users will have a broken download.
So, if you have too much data, you can just write to the stream in memory, just change php://output to php://memory and move something around:
<?php $fp = fopen('php://memory','rw'); // our generateData() function might throw an exception, in which case // we want to fail gracefully, not send the user a broken/incomplete csv. try { while($row = generateData()) fputcsv($fp, $row); }catch(\Exception $e){ // display a nice page to your user and exit/return } // SUCCESS! - so now we have CSV data in memory. Almost like we'd spooled it to a file // on disk, but we didn't touch the disk. //rewind our file handle rewind($fp); //send output header('Content-type: text/csv; charset=UTF-8'); header('Content-disposition: attachment; filename=report.csv'); stream_get_contents($fp);
source share