1

所以我今天安装了 Laravel Debugbar,试图让我的本地开发人员获得更好的体验,而且在大多数情况下,它确实如此。但是,当我尝试下载从 PhpOffice\PhpSpreadsheet ( https://phpspreadsheet.readthedocs.io/en/latest/ ) 生成的 Excel 时,出现了一个问题,这是有问题的代码片段:

$excelFile = new Spreadsheet();
// Load stuff from DB in Sheets, etc. etc.
$writer = new Xlsx($excelFile);
$filename = 'testing.xlsx';
$writer->save('php://output');

这很好用,内容可以.xlsx毫无问题地作为文件加载和下载。当我打开文件时,我收到此警报:

我们发现“testing.xlsx”中的某些内容存在问题。你想让我们尽可能多地恢复吗?如果您信任此工作簿的来源,请单击“是”。

我单击“是”,然后收到此警报:

Excel 能够通过修复或删除不可读的内容来打开文件。

我单击“删除”并打开我的文件,没有删除任何内容(将文件与master分支上​​的先前提交进行比较,没有更改)。

现在这是有趣的部分,我只有在启用 Debugbar 时才会收到此警报。在.env中,我有DEBUGBAR_ENABLED=true,如果我将其设置为DEBUGBAR_ENABLED=false并重新加载/重新下载,我不会收到警报。有没有人见过这个问题?为什么 Debugbar 会搞砸这个?是不是$writer->save('php://output');被 Debugbar 的注入污染了?

旁注,这将不是问题production,因为 Debugbar 是一个require-dev依赖项,但我只是好奇我是否可以在本地开发期间避免这种情况。

4

1 回答 1

0

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.

于 2021-01-06T20:55:34.170 回答