stkertix
stkertix

Reputation: 81

PhpSpreadsheet MimeType generate vnd.ms-office instead of vnd.ms-excel

I'm using PhpSpreadsheet to generate Excel (.xls) file.

then I realize the mimetype of the generated file was application/vnd.ms-office.

Test with two methods:

Using this to direct download to server dir:

<?php
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

$writer = new Xls($spreadsheet);

$filename = 'name-of-the-generated-file.xls';
$writer->save(FCPATH . 'extracted/' . $filename);

and using this to download with browser

<?php
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

$writer = new Xls($spreadsheet);

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="name-of-the-generated-file.xls"'); 
header('Cache-Control: max-age=0');

$writer->save('php://output');

I check the generated file with

echo mime_content_type('name-of-the-generated-file.xls');

both of code generate application/vnd.ms-office mime.

how to generate spreadsheet with application/vnd.ms-excel instead of application/vnd.ms-office?

Upvotes: 0

Views: 1729

Answers (1)

Mark Baker
Mark Baker

Reputation: 212452

Don't trust mime_content_type() to give any meaningful answer.... it uses magic.mime to identify filetypes, and that has an over-simplistic approach (typically based on just a few bytes) that doesn't delve too deeply into the structure of the file itself. When sending a file to the browser, then the Content Type header is what tells the browser how to handle the file, and the correct mime types to send for Excel are application/vnd.ms-excel for xls files, and application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for xlsx files.

Upvotes: 1

Related Questions