Skip to content Skip to sidebar Skip to footer

Compress Html Output From Zend Framework 2

I'm currently using Zend Framework 2 beta for on PHP 5.4.4 to develop a personal webapp for self-study purpose. I was wondering if it is possible to intercept the html output just

Solution 1:

Yep, you can:

On Modle.php create an event that will trigger on finish

publicfunctiononBootstrap(Event $e)
{
    $app = $e->getTarget();
    $app->getEventManager()->attach('finish', array($this, 'doSomething'), 100);
}


publicfunctiondoSomething ($e)
{
    $response = $e->getResponse();
    $content = $response->getBody();
    // do stuff here$response->setContent($content);

}

Solution 2:

Just put this two method inside any module.php . It will gzip and send compressed out put to the browser.

publicfunctiononBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();
    $eventManager->attach("finish", array($this, "compressOutput"), 100);
}

publicfunctioncompressOutput($e)
    {
        $response = $e->getResponse();
        $content = $response->getBody();
        $content = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '#(?://)?<![CDATA[(.*?)(?://)?]]>#s'), array('>', '<', '\\1', "//&lt;![CDATA[n" . '1' . "n//]]>"), $content);

        if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
            header('Content-Encoding: gzip');
            $content = gzencode($content, 9);
        }

        $response->setContent($content);
    }

Post a Comment for "Compress Html Output From Zend Framework 2"