1

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.

4

2 回答 2

0

为什么需要将 csv 内容写入 tmp 文件/php 的输出流?

您只需要直接回显 csv 内容,不应该有任何文件操作

  • 发送适当的附件标题
  • 回显 csv 内容。

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;
于 2012-08-31T08:29:12.540 回答
0

fpassthru()将在较低级别执行您正在执行的操作。像这样使用它:

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

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

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

即使它可能是一个 csv 文件,也没有必要限制自己使用 csv 函数,除非您在输出时生成文件。

如果您将 CSV 流式传输到输出而不是文件,您可能会看到性能提升。

于 2012-08-31T08:22:31.380 回答