压缩来自 zend 框架 2 的 html 输出


Compress html output from zend framework 2

我目前正在使用 PHP 5.4.4 上的 Zend Framework 2 beta 来开发一个用于自学目的的个人 Web 应用程序。

我想知道是否可以在将 html 输出发送到浏览器之前拦截它,以便通过删除所有不必要的空格来缩小它。

如何在 ZF2 中实现此结果?

是的,你可以:

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

只需将这两个方法放在任何模块中.php .它将 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);
    }