MNB PHPExcelDeveloper Guide
Writing workbooks

Send a Workbook as a Browser Download

Generate the file outside the web root and stream it with correct HTTP headers and cleanup.

Updated

LevelIntermediateReading time8 minPackagemnb/mnb-phpexcel
save()safeFileName()saveSafe()

What you will learn

  • Avoid corrupting binary output with HTML or whitespace.
  • Use safe filenames and temporary paths.
  • Clean up generated files after delivery.

Generate into a temporary directory#

PHP
$filename = MnbExcel::safeFileName('Monthly Sales July 2026', 'xlsx');
$path = __DIR__ . '/../storage/temporary/' . $filename;

MnbExcel::report($rows)
    ->withHeader()
    ->autoWidth()
    ->save($path);

Send correct response headers#

download-report.php
if (!is_file($path)) {
    http_response_code(404);
    exit('Report not found.');
}

while (ob_get_level() > 0) {
    ob_end_clean();
}

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Length: ' . filesize($path));
header('Cache-Control: private, no-store');

readfile($path);
unlink($path);
exit;

Protect the download endpoint#

  • Authorize the current user before generating the file.
  • Do not accept arbitrary output paths.
  • Use rate limits for expensive reports.
  • Generate large reports through a queue and return a signed download URL.
  • Clean expired temporary exports with a scheduled maintenance job.