Compress html output from zend framework 2

痞子三分冷 提交于 2020-04-13 09:01:11

问题


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 before it is sent to the browser in order to minify it by removing all unnecessary white spaces.

How could I achieve this result in ZF2?


回答1:


Yep, you can:

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

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


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

}



回答2:


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

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

public function compressOutput($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);
    }


来源:https://stackoverflow.com/questions/11309904/compress-html-output-from-zend-framework-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!