Skip to content

How to compress html output in zend framework 2 ?

Last updated on December 21, 2022

Today’s post is About HTML Output Compression, we can reduce 10-20% load on the server by compressing the HTML output(bandwidth save, faster page loading)

we can easily compress the HTML Output in Zend Framework 2, with the help of zf2 events.

On your main Modle.php create an event that will trigger on the finish,

module/application/modle.php

public function onBootstrap(Event $e) {
    $app = $e->getTarget();
    $app->getEventManager()->attach('finish', array($this, 'outputCompress'), 100);
}

public function outputCompress($e) {
	$response = $e->getResponse();
	$response->setContent($this->_compress($response->getBody()));
}
    
	
private function _compress($content) {
		$search = array(
			'/>[^S ]+/s',
			'/[^S ]+#s' //leave CDATA alone
		);
		$replace = array(
			'>',
			'<',
			'\1',
			"//<![CDATA[n".'1'."n//]]>"
		);
	    return  preg_replace($search, $replace, $content);
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments