Danielson Silva
Danielson Silva

Reputation: 178

Php send 0 bytes excel file through echo

I am creating a very large table in a single string $output with the data from a MySQL database. In end of the php script, I send two headers:

header("Content-type: application/msexcel");
header("Content-Disposition: attachment; filename=action.xls");

The problem is when the large table has about more than 55000 rows. When this happens, the file sent is 0 bytes and the user opens a empty file. I am sending the file through this after the headers:

echo $output;

When the table has not too many rows, the file sent work. How to send a file in this way that the size of the string $output don't matter?

Upvotes: 0

Views: 560

Answers (2)

Danielson Silva
Danielson Silva

Reputation: 178

The solution found in another question worked for this. The file is too large to send, so the solution is send part by part to the user. Instead of use readfile() function, use the readfile_chuncked() customized function:

define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk

// Read a file and display its content chunk by chunk
function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt    = 0;
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }

    while (!feof($handle)) {
        $buffer = fread($handle, CHUNK_SIZE);
        echo $buffer;
        ob_flush();
        flush();

        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }

    $status = fclose($handle);

    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}

Upvotes: 0

FULL STACK DEV
FULL STACK DEV

Reputation: 15971

header("Content-type: application/msexcel");
header("Content-Disposition: attachment; filename=action.xls");

Move these lines to the top the page or Script before html table it will starts working

Upvotes: 1

Related Questions