PHP efficiently write and output csv files using fputcsv

filefputcsvPHP

When writing .csv files i use fputcsv like this:

- open a temporary file $f = tmpfile();
- write content to file using fputcsv($f,$csv_row);
- send appropriate headers for attachment
- read file like this:

# move pointer back to beginning 
rewind($f);

while(!feof($f))
    echo fgets($f);

# fclose deletes temp file !
fclose($f);

Another aproach would be:

- open file $f = fopen('php://output', 'w');
- send appropriate headers for attachment
- write content to file using fputcsv($f,$csv_row);
- close $f stream

My question is: What would be the best approach to output the data faster and taking into account server resources ?

First method would use more writes and consume more resources but would output very fast.

Second method uses less writes and would output slower i think.

Eagerly waiting for your opinions on this.

Thanks.

Best Answer

fpassthru() will do what you're doing at a lower level. Use it like this:

# move pointer back to beginning 
rewind($f);

while(fpassthru($f) !== false);

# fclose deletes temp file !
fclose($f);

Even though it may be a csv file, there is no need to restrict yourself to csv functions, unless you are generating the file at the time of output.

You could probably see a performance gain if you stream the CSV to output instead of to a file.