【发布时间】:2015-08-11 05:16:47
【问题描述】:
private function convert_to_csv($input_array, $output_file_name, $delimiter) {
$temp_memory = fopen('php://memory','w');
foreach ($input_array as $line) {
fputcsv($temp_memory, $line, $delimiter);
}
fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}
我使用上面的函数来获取一个数据数组,转换为 CSV,然后输出到浏览器。两个问题:
- 通过 HTTP 下载后文件是否从内存中删除?
- 如何重写相同的函数,以便文件可以使用(例如,用作通过 PHPMailer 发送的电子邮件附件),然后立即从内存中删除?
编辑:工作代码 - 但写入文件,而不是内存
public function emailCSVTest() {
$test_array = array(array('Stuff','Yep'),array('More Stuff','Yep yep'));
$temp_file = '/tmp/temptest.csv';
$this->convertToCSV($test_array, $temp_file);
$this->sendUserEmail('Test Subject','Test Message','nowhere@bigfurryblackhole.com',$temp_file);
unlink($temp_file);
}
private function convertToCSV($input_array, $output_file) {
$temp_file = fopen($output_file,'w');
foreach ($input_array as $line) {
fputcsv($temp_file, $line, ',');
}
fclose($temp_file);
}
仍然没有答案:原始函数是否会从内存中删除文件?
【问题讨论】:
-
我只需将文件存储在文件系统上(例如
/tmp),发送邮件(带附件),然后在文件名上调用unlink()。 -
因此将第一行更改为 $temp_file = fopen('/tmp/abc.csv','w'),创建文件,然后将 fseek >> fpassthru 替换为 return $temp_file,跟进带有 unlink($temp_file) 的父函数?
-
类似的东西,是的。不要忘记先
fclose()文件。 (在unlink()之前) -
谢谢!上面添加了工作示例。
-
如果您需要它是易失性的,为什么您首先要写入文件?