简体   繁体   English

压缩zend框架2的html输出

[英]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. 我目前正在使用Zend Framework 2 beta for PHP 5.4.4来开发一个用于自学目的的个人webapp。

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. 我想知道是否有可能在发送到浏览器之前拦截html输出,以便通过删除所有不必要的空格来缩小它。

How could I achieve this result in ZF2? 我怎样才能在ZF2中实现这个结果?

Yep, you can: 是的,你可以:

On Modle.php create an event that will trigger on finish 在Modle.php上创建一个将在完成时触发的事件

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);

}

Just put this two method inside any module.php . 只需将这两个方法放在任何module.php中。 It will gzip and send compressed out put to the browser. 它会gzip并将压缩输出发送到浏览器。

 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM