在内存、电子邮件中创建 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 发送的电子邮件附件),然后立即从内存中删除?

编辑:工作代码 - 但写入文件,而不是内存

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/