在内存、电子邮件中创建CSV,并从内存中删除


Create CSV in memory, email, and remove from memory

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,并输出到浏览器。两个问题:

  1. 通过HTTP下载后文件是否从内存中删除?
  2. 如何重写相同的函数,以便文件可以使用(例如,使用PHPMailer发送的电子邮件附件),然后立即从内存中删除?

EDIT: Working Code - But write to file, not memory

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);
}

仍未回答:原始函数是否从内存中删除文件,还是没有?

我会使用PHP的temp fopen包装器和内存阈值,像这样:

// we use a threshold of 1 MB (1024 * 1024), it's just an example
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if ($fd === false) {
    die('Failed to open temporary file');
}
$headers = array('id', 'name', 'age', 'species');
$records = array(
    array('1', 'gise', '4', 'cat'),
    array('2', 'hek2mgl', '36', 'human')
);
fputcsv($fd, $headers);
foreach($records as $record) {
    fputcsv($fd, $record);
}
rewind($fd);
$csv = stream_get_contents($fd);
fclose($fd); // releases the memory (or tempfile)

内存阈值为1MB。如果CSV文件变大,PHP将创建一个临时文件,否则将在内存中进行操作。优点是大的CSV文件不会耗尽内存。

关于你的第二个问题,fclose()将释放内存。

我曾经写过一篇关于这个的博客文章,你可能会觉得很有趣:http://www.metashock.de/2014/02/create-csv-file-in-memory-php/