Create CSV in memory, email, and remove from memory

后端 未结 1 2088
青春惊慌失措
青春惊慌失措 2021-02-08 16:30
private function convert_to_csv($input_array, $output_file_name, $delimiter) {

    $temp_memory = fopen(\'php://memory\',\'w\');

    foreach ($input_array as $line) {
         


        
相关标签:
1条回答
  • 2021-02-08 17:22

    I would make use PHP's temp fopen wrapper together with threshold of memory like this:

    // 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)
    

    The memory treshold is 1MB. If the CSV file get's larger, PHP would create a temporary file, otherwise all will happen in memory. The advantage is that large CSV files won't exhaust the memory.

    About your second question, fclose() will release the memory.

    I once wrote a blog article regarding to this, you may find it interesting: http://www.metashock.de/2014/02/create-csv-file-in-memory-php/

    0 讨论(0)
提交回复
热议问题