1
votes

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.

2
This is not about opinions. We don't think one or the other is faster. Try benchmarking both approaches, and you'll know which one is faster.Berry Langerak
@BerryLangerak Yes, you are right. I'll try benchmarking this and post results.B Paul

2 Answers

0
votes

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.

0
votes

Why do you need to write the csv content to a tmp file/php's output stream ?

You just need to echo the csv content directly, there should not be any file operations.

  • send appropriate headers for attachment
  • echo the csv content.

header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

foreach ($csv_rows as $csv_row) {
  echo $csv_row;
}
exit;