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()
函数删除该文件。 - Niek van der Steenfclose()
关闭文件。(在unlink()
之前) - Niek van der Steen