So I installed Laravel Debugbar today in an attempt to make my local dev a better experience, and for the most part, it has. An issue has arisen though when I try to download an Excel generated from PhpOffice\PhpSpreadsheet (https://phpspreadsheet.readthedocs.io/en/latest/) Here's a snippet of the code in question:
$excelFile = new Spreadsheet();
// Load stuff from DB in Sheets, etc. etc.
$writer = new Xlsx($excelFile);
$filename = 'testing.xlsx';
$writer->save('php://output');
This works great, and the content is loaded into and downloaded as an .xlsx
file without issue. When I open the file, I get this alert:
We found a problem with some content in 'testing.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.
I click "Yes", and then I get this alert:
Excel was able to open the file by repairing or removing the unreadable content.
I click "Delete" and my file is opened, with nothing deleted (compared file against previous commit on master
branch, no change).
Now here's the fun part, I only get this alert when Debugbar is enabled. In .env
, I have DEBUGBAR_ENABLED=true
, and if I set that to DEBUGBAR_ENABLED=false
and reload/redownload, I don't get the alert. Has anyone seen this issue before? Why would Debugbar be messing with this? Is it an issue with $writer->save('php://output');
being polluted by Debugbar's injection?
Sidenote, this will be a non-issue in production
, as Debugbar is a require-dev
dependence, but I'm just curious if I can avoid this during local development or not.
Apparently, this has been asked and answered on the official documentation; was just a little tricky to find. I was correct about object pollution via debugbar, and the simply soultion was to add exit();
after $writer->save();
:
$excelFile = new Spreadsheet();
// Load stuff from DB in Sheets, etc. etc.
$writer = new Xlsx($excelFile);
$filename = 'testing.xlsx';
$writer->save('php://output');
exit();
There were a couple more notes about ob_clean()
and/or ob_end_clean()
, ob_flush()
, etc etc., but none of those worked with Laravel + Debugbar. For reference:
https://github.com/PHPOffice/PhpSpreadsheet/issues/217
Sidenote, this prevents Debugbar from handling the GET
or POST
request associated with the Excel download, so there's some give and take required. Simply commenting out the exit()
locally will allow debugging, but the Excel will be marked as corrupt. Simple repeat action with exit()
on will handle.