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:

1
2
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
namespace replace-this-line-with-your-namespace;

use Symfony\Component\HttpKernel\HttpKernelInterface,
    Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class MSExcelListener
{

    /**
     * Adds the headers to the response once it's created
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        // Only master requests are handled
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            return;
        }

        // Check if response is serving an "vnd.ms-excel" file
        if (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):

1
2
3
<service id="listener_msexcel_tweak" class="<YourBundleName>\Listener\MSExcelListener" public="true">
  <tag name="kernel.event_listener" event="kernel.response" />
</service>

If the response content-type is a vnd.ms-excel file and the site is running over HTTP, the two headers are automatically added.

Comments