问题
I'm currently using Zend Framework 2 beta for on PHP 5.4.4 to develop a personal webapp for self-study purpose.
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.
How could I achieve this result in ZF2?
回答1:
Yep, you can:
On Modle.php create an event that will trigger on finish
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);
}
回答2:
Just put this two method inside any module.php . It will gzip and send compressed out put to the browser.
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);
}
来源:https://stackoverflow.com/questions/11309904/compress-html-output-from-zend-framework-2