unixo's blog

PHPExcel and Symfony2

Recently, for a website I developed using Symfony 2, I
needed to export some data in Microsoft Excel format. As you may expect, there is already
a great bundle to integrate PHPExcel into your Symfony-based project, the
ExcelBundle by liuggio.

As stated in bundle documentation, if you are using a HTTPS connection, you have to set
these two headers in your response for compatibility with IE<9:

By the way, as I had to generate a lot of reports and, instead of adding these two more lines,
I decided to write a response listener: let’s describe these two simple steps.

First of all create a new file named MSExcelListener.php and store under the Listener folder of
your bundle. Here the content of the file.

123456789101112131415161718192021222324252627282930313233343536

<?phpnamespacereplace-this-line-with-your-namespace;useSymfony\Component\HttpKernel\HttpKernelInterface,Symfony\Component\HttpKernel\Event\FilterResponseEvent;classMSExcelListener{/** * Adds the headers to the response once it's created */publicfunctiononKernelResponse(FilterResponseEvent$event){// Only master requests are handledif(HttpKernelInterface::MASTER_REQUEST!==$event->getRequestType()){return;}// Check if response is serving an "vnd.ms-excel" fileif(preg_match('/vnd.ms-excel/',$event->getResponse()->headers->get('Content-Type'))){/** * If you are using a https connection, you have to set those two * headers for compatibility with IE <9 */if(!empty($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off'||$_SERVER['SERVER_PORT']==443){$response=$event->getResponse();$response->headers->set('Pragma','public');$response->headers->set('Cache-Control','maxage=1');$event->setResponse($response);}}}}?>

Next step is registering the listener, so that Symfony kernel calls it before the response is
sent to the client: simply add these lines to your configuration (just like you register a new
service):