【问题标题】:Compress html output from zend framework 2压缩来自 zend 框架 2 的 html 输出
【发布时间】:2012-07-03 11:25:25
【问题描述】:

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

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

如何在 ZF2 中实现这个结果?

【问题讨论】:

    标签: php zend-framework2 output-buffering html-manipulation


    【解决方案1】:

    是的,你可以:

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

    【讨论】:

    • 如果我的应用由多个模块组成,我应该把它放在哪个模块上? “主”模块,还是全部?无论如何,我会尽快尝试。
    • 我把一般事件放在Application下。但它适用于任何一个模块
    【解决方案2】:

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

    【讨论】:

    • 对此正则表达式的一点解释会有所帮助...目前它会破坏任何 HTML。
    猜你喜欢
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 2013-05-04
    相关资源
    最近更新 更多