我使用 PHP 的 fputcsv()
为来自 MySQL 数据库的一些记录提供服务,方法是在服务器上创建一个文件,填充它,然后在下一页链接到它。
这很好用,但是因为这可能是敏感数据,所以我不希望在为(可能)一次性下载而创建文件时在服务器上挂起大量文件。
所以我想知道的是:有没有一种方法可以创建此文件并提供下载服务,而无需在服务器上实际写入永久文件?
例如,我可以创建一个逗号分隔的字符串而不是使用 fputcsv()
并将其与输出缓冲区中的正确 header 一起提供吗?
明显的做法是删除文件,但我需要等到客户端先下载它,这使得决定何时删除文件有点困难。
欢迎提出建议
代码:
$fp = fopen($filename, 'w');
fputcsv($fp, array("Last Name", "First Name"));
foreach ($result as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
最佳答案
fputcsv() 是一个很棒的小函数,所以我不会放弃它。
相反,我建议您尝试使用 PHP 的内置 I/O Wrappers
例如,您可以执行此操作以逐行“流式传输”您的 CSV 数据(受各种输出缓冲区的影响,但这是另一回事):
<?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);
效果很好,但如果出现问题,您的用户将无法下载。
所以,如果你没有太多数据,你可以只写入内存流,只需将 php://output
换成 php://memory
并四处移动:
<?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);
关于php - 如何将输出作为文件提供而不将其保存在服务器上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12003495/