While exporting data from database to a file via PHP, such libraries as PHPExcel will cause an error Memory limit exceeded. Because they read data from database to RAM.

You can avoid that using file system only. So the recepy is:Get data from database and write it to a temporary file and then read it directly to stdout

function getExport(\PDO $conn) {
    $file = fopen( '/tmp/export.txt', 'a' );
    $sql = 'SELECT data FROM export_table ORDER BY name';
    foreach($conn->query($sql) as $row) {
        fwrite($file, $row['data']);
    }
    fclose($file);
    header('Set-Cookie: fileDownload=true; path=/');
    header('Content-Encoding: UTF-8');
    header('Content-Type: text; charset=utf-8');
    header("Content-Disposition: attachment; filename=export.txt");

    //read our file from file system without using RAM to output
    readfile('/tmp/export.txt');unlink( '/tmp/export.txt' );
}

Leave a Reply

Your email address will not be published. Required fields are marked *