'PHPExcel_IOFactory::createWriter causes wrong behaviour
After having created a PHPExcel program, the final step consists of saving the worksheets, to do that, I want to apply these rules so as to generate the file in Excel 2007:
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="workbook1.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
Instead of getting the Excel2007 file, the ouptut with any kind of browser is something like:
07:31:12 Create new PHPExcel object 07:31:12 Set properties 07:31:12 Add some data 07:31:12 Rename sheet 07:31:12 Write to Excel2007 format PKæ;È< —![[Content_Types].xml”MNÃ0…÷=…å-Jܲ@%í‚Â*Q`ìIcÕ±-{úw{&I ˆE j7±"û½oüg÷œ%”NKë”ü‰Ï¦£by‰]*y„Hª†F¦Üp4SùØH¤ß¸Aªµ\¸ï„òÁa†ŸŽXñJD£-dÄÙHì .....
I tried with various browsers but I get the same result. On the other hand, if I save the file with these lines below, it works fine:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('/usr/local/myWorkbooks/workbook1.xlsx');
Any idea why it does not work through my browser? Thanks in advance for your help
Solution 1:[1]
If you're streaming the output to php://output then you must not echo anything else to that output stream. You're clearly echoing the lines:
07:31:12 Create new PHPExcel object
07:31:12 Set properties
07:31:12 Add some data
07:31:12 Rename sheet
07:31:12 Write to Excel2007 format
to output before the Excel file itself
Remove those echo lines
This is standard PHP behavior, and a question that has been answered here thousands of times in the past: echoes go to php://output.... I'm surprised you're not also getting a "headers already sent" error as well
Solution 2:[2]
You have to clean the output buffer and turn off buffering using ob_end_clean()
before saving. Do this instead:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="workbook1.xlsx"');
header('Cache-Control: max-age=0');
ob_end_clean();
$objWriter->save('php://output');
exit;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mark Baker |
Solution 2 |