【发布时间】:2016-05-10 04:42:21
【问题描述】:
我是 zend 的新手。我已经使用 zend 框架开发了一个网站。现在,我想在我的网站中设置 gzip 压缩。请您指导我逐步实现这一点。
提前致谢。 卡马尔·阿罗拉
【问题讨论】:
标签: optimization zend-framework
我是 zend 的新手。我已经使用 zend 框架开发了一个网站。现在,我想在我的网站中设置 gzip 压缩。请您指导我逐步实现这一点。
提前致谢。 卡马尔·阿罗拉
【问题讨论】:
标签: optimization zend-framework
在您的网站中有两种 gzip 输出的方法。
使用网络服务器。如果您的网络服务器是 apache,您可以参考 here 获取有关如何在您的服务器上启用 mod_deflate 的良好文档。
使用 zend 框架。尝试以下来自this website 的代码。 在引导文件中创建一个 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 代码发送给用户。
【讨论】:
我根据您的提示为 zend 框架 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);
}
【讨论】:
尊重 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',
"//<![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', "//<![CDATA[n".'1'."n//]]>"), $content);
if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}
【讨论】: