Home >Backend Development >PHP Tutorial >How to Force CSV File Downloads in PHP: A Header and `.htaccess` Approach?
When a CSV file opens in a browser window upon clicking a link instead of downloading, modifications to the code and server settings are required.
The suggested approach in question 2, creating a separate PHP file (csv.php) to handle the download, should work as intended. However, an alternative approach is to use the header() and readfile() functions directly in the HTML page. This method ensures the actual CSV file is downloaded.
Set the appropriate headers:
header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename="example.csv"'); header('Pragma: no-cache');
Output the CSV file contents using readfile():
readfile("/path/to/example.csv");
As a more universal solution, you can force all CSV files to download using a modification in the .htaccess file:
AddType application/octet-stream csv
By implementing one of these solutions, you can successfully force CSV files to download instead of being displayed in the browser window.
The above is the detailed content of How to Force CSV File Downloads in PHP: A Header and `.htaccess` Approach?. For more information, please follow other related articles on the PHP Chinese website!