Create Word, Excel, and CSV Files with PHP

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/phpword

PhpSpreadsheet creates XLSX files and PHPWord creates DOCX files. Authorize downloads and neutralize spreadsheet-formula prefixes in untrusted exported values.

See PHP’s fputcsv() reference.

admin

admin

Leave a Reply

Your email address will not be published.