Last updated: August 27, 2026.
Create genuine file formats instead of sending HTML with a DOC or XLS extension. Use fputcsv() for CSV and maintained libraries for DOCX and XLSX.
<?php
declare(strict_types=1);
$rows = [['Name', 'Email'], ['Ada Lovelace', '[email protected]']];
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="contacts.csv"');
$output = fopen('php://output', 'wb');
foreach ($rows as $row) {
fputcsv($output, $row, ',', '"', '');
}
fclose($output);composer require phpoffice/phpspreadsheet
composer require phpoffice/phpwordPhpSpreadsheet creates XLSX files and PHPWord creates DOCX files. Authorize downloads and neutralize spreadsheet-formula prefixes in untrusted exported values.
See PHP’s fputcsv() reference.
Exporting database reports? PHPRunner includes export and reporting features.