Download xlsx file using php

24,425

Solution 1

After many years, I got same problem, and after searching, I got here again ))

This is solution, that worked for me:

$file = "somefile.xlsx";
// define file $mime type here
ob_end_clean(); // this is solution
header('Content-Description: File Transfer');
header('Content-Type: ' . $mime);
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file) . "\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);

Solution 2

You must be using this code in middle of some other file.

The problem with headers is they need to be set first on a page. They will not work if you have even 1 single space echoing before them. So you need to ob_clean() [clean the buffer] before you are setting headers

Try

    ob_clean();
    flush();
    $file = "somefile.xlsx";
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);

Solution 3

Remove:

ob_clean();
flush();

Add at the end of code:

exit();

The issue is that flush() will also throw in your *.xlsx file content some garbage it has in it and that will corupt your file, even if you use ob_clean();

For a better understanding go to php.net and read the difference between flush(), ob_flush() and find that you didn't even need them in the first case. Therefore you won't need the ob_clean() too.

Share:
24,425
Oto Shavadze
Author by

Oto Shavadze

Updated on July 09, 2022

Comments

  • Oto Shavadze
    Oto Shavadze almost 2 years

    I need make xlsx file download from my site (but not from directly open file url like this: http://site.com/file.xlsx )

    So, this is php code

            $file = "somefile.xlsx";
            header('Content-Description: File Transfer');
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
    

    file is downloaded, his extension is .xlsx, but when trying open this file in ms excel, file not opened and I got error : excel cannot open the file.xlsx because the file format or file extension is not valid

    Tell please, why this happened? where I am wrong?