如何在Zend Framework网站中设置gzip压缩

4

我是全新使用zend的。我已经用zend框架开发了一个网站。现在,我想在我的网站中设置gzip压缩。您能按步骤指导我如何实现吗?

提前感谢。 kamal Arora

3个回答

5
我使用您的提示为Zend Framework 2(ZF2)创建了这个内容。
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 = str_replace("  ", " ", str_replace("\n", " ", str_replace("\r", " ", str_replace("\t", " ", $content))));

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

    $response->setContent($content);
}

5
有两种方法可以在您的网站上压缩输出。
  1. 使用Web服务器。如果您的Web服务器是apache,您可以参考这里来了解如何在服务器上启用mod_deflate的详细说明。

  2. 使用zend框架。请尝试以下代码,代码来源于这个网站。 在您的引导文件中创建一个gzip压缩的字符串。

代码:

try {
 $frontController = Zend_Controller_Front::getInstance();
 if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
    ob_start();
    $frontController->dispatch();
    $output = gzencode(ob_get_contents(), 9);
    ob_end_clean();
    header('Content-Encoding: gzip');
    echo $output;
} else {
    $frontController->dispatch();
}
} catch (Exeption $e) {
if (Zend_Registry::isRegistered('Zend_Log')) {
    Zend_Registry::get('Zend_Log')->err($e->getMessage());
}
$message = $e->getMessage() . "\n\n" . $e->getTraceAsString();
/* trigger event */
}

GZIP并不压缩图像,只是将网站发送到用户的原始HTML/CSS/JS/XML/JSON代码进行压缩。


1

针对 Bruno Pitteli 的回答,我认为您可以按照以下方式进行压缩:

$search = array(
    '/\>[^\S ]+/s',  // strip whitespaces after tags, except space
    '/[^\S ]+\</s',  // strip whitespaces before tags, except space
    '/(\s)+/s',       // shorten multiple whitespace sequences
    '#(?://)?<![CDATA[(.*?)(?://)?]]>#s' //leave CDATA alone
);

$replace = array(
    '>',
    '<',
    '\\1',
    "//&lt;![CDATA[n".'1'."n//]]>"
);

$content = preg_replace($search, $replace, $content);

所以完整的代码示例现在看起来像这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接