B Paul
B Paul

Reputation: 11

PHP efficiently write and output csv files using fputcsv

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.

Upvotes: 1

Views: 7428

Answers (2)

xdazz
xdazz

Reputation: 160853

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;

Upvotes: 0

Lucas Green
Lucas Green

Reputation: 3959

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.

Upvotes: 0

Related Questions