PHP xlsx header: Why Binary Headers Matter for Excel Downloads
You might assume that serving a file via HTTP is as simple as setting the Content-Type and sending the file body. If you've successfully downloaded PDFs using a basic PHP script, that assumption feels validated. However, binary formats like .xlsx, .zip, or archives require stricter handling of headers to ensure the client accepts them without corruption.
Consider a scenario where you have a valid Excel file, myfile.xlsx, located in the same directory as your PHP script. A simple implementation might look like this:
<?php
header('Content-disposition: attachment; filename=myfile.xlsx');
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
readfile('myfile.xlsx');
?>
When a user clicks the download link associated with this script, the browser initiates the transfer. The file saves to disk successfully. Yet, upon opening it in Excel, you encounter an error: "Excel cannot open the file... because the file format or file extension is not valid." The file opens fine if opened manually from the filesystem, indicating the file content itself is intact.
The issue lies in how the browser interprets the HTTP response. While PDFs are often forgiving of minor header discrepancies due to their internal structure and robust parsers, Excel files are fundamentally ZIP archives containing XML documents. They are strict about binary integrity. When a web server or PHP script outputs data before the headers are fully processed or if output buffering interferes, it can introduce invisible characters (like BOMs) or truncate the stream.
The solution identified in community discussions involves explicitly cleaning any existing output and setting specific headers that enforce binary transfer. The refined implementation looks like this:
<?php
$file = "myfile.xlsx";
// Clean any existing buffer to prevent accidental character injection
ob_clean();
flush();
// Set the download filename
header('Content-disposition: attachment; filename='.$file);
// Explicitly define the MIME type for Excel 2007+
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// Inform the server how large the file is
header('Content-Length: ' . filesize($file));
// Crucial: Tell the browser to treat the content as binary, not text
header('Content-Transfer-Encoding: binary');
// Force cache invalidation to ensure users get fresh data
header('Cache-Control: must-revalidate');
header('Pragma: public');
// Send headers and flush them immediately before reading the file
ob_clean();
flush();
// Finally, read and send the file content
readfile($file);
?>
The addition of Content-Transfer-Encoding: binary is particularly critical. Without it, some browsers might attempt to interpret the incoming bytes as text or apply character set conversions, corrupting the binary structure of the ZIP archive inside the .xlsx file. The ob_clean() and flush() calls ensure that no partial output (such as whitespace from previous scripts) pollutes the response stream before the headers are sent.
In a WAMP environment or any standard PHP setup, this approach ensures the HTTP response matches what Excel expects: a clean binary stream with a correct MIME type. For developers building dynamic dashboards where data is generated on the fly rather than stored as static files, these header details become even more vital to prevent silent data corruption. If you are working within a Laravel application, ensuring these headers are set before any other output occurs is equally important to maintain file integrity during exports.