Compress HTML output with CodeIgniter

What it does

  • removes useless whitespace from HTML generated by CodeIgniter
  • works perfectly with CodeIgniter caching

How

check hooks are enabled

system/application/config/config.php

$config['enable_hooks'] = TRUE;

declare a new hook

system/application/config/hooks.php

// compress output
$hook['display_override'][] = array(
	'class' => '',
	'function' => 'compress',
	'filename' => 'compress.php',
	'filepath' => 'hooks'
	);

add the hook

system/application/hooks/compress.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
function compress()
{
	$CI =& get_instance();
	$buffer = $CI->output->get_output();
 
	 $search = array(
		'/\n/',			// replace end of line by a space
		'/\>[^\S ]+/s',		// strip whitespaces after tags, except space
		'/[^\S ]+\</s',		// strip whitespaces before tags, except space
	 	'/(\s)+/s'		// shorten multiple whitespace sequences
	  );
 
	 $replace = array(
		' ',
		'>',
	 	'<',
	 	'\\1'
	  );
 
	$buffer = preg_replace($search, $replace, $buffer);
 
	$CI->output->set_output($buffer);
	$CI->output->_display();
}
 
/* End of file compress.php */
/* Location: ./system/application/hools/compress.php */

Notes

  • “cleaning code” from Tobias Goldkamp (with a minor addition to replace ends of lines by spaces). If you have problems with inline Javascript, try the code from Fatih Bazman below (#2).
  • possible to use HTML Tidy instead:
$options = array(
	'clean' => true,
	'hide-comments' => true,
	'indent' => true
	);
 
$buffer = tidy_parse_string($buffer, $options, 'utf8');
tidy_clean_repair($buffer);
 
// warning: if you generate XML, HTML Tidy will break it (by adding some HTML: doctype, head, body..) if not configured properly
 

Feedback

i got the CIOrgasm with this function. this is what i looking for for this last year.thx
believeMeYouDontWannaKnow
August 18, 2009
#1
Hello Jerome,

Thanks for coding. But I have noticed that Javascript codes doesn't works in codes, if codes are in "//" signs. Therefore, I revised your codes (actually Tobias Goldkamp side) like as below:
function compress()
{
 $CI =& get_instance();
 $buffer = $CI->output->get_output();
 
 $search = array(
    '/\>[^\S ]+/s', 
    '/[^\S ]+\</s', 
     '/(\s)+/s', // shorten multiple whitespace sequences
  '#(?://)?<!\[CDATA\[(.*?)(?://)?\]\]>#s' //leave CDATA alone
  );
 $replace = array(
     '>',
     '<',
     '\\1',
  "//&lt;![CDATA[\n".'\1'."\n//]]>"
  );

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

 $CI->output->set_output($buffer);
 $CI->output->_display();
}
Regards
Fatih Bazman
September 18, 2009
#2
are there any benchmarks to show how effective this step is? or does this exist more for code obfuscation?
matt
November 5, 2009
#3
Matt, it's mainly to show how easy it is to alter CodeIgniter output. However, with HTMLTidy, it can be used to remove comments, make sure the HTML is always correct, etc
Jérôme Jaglale
February 1, 2010
#4
&lt;?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

function compress()
{
$CI =& get_instance();
$buffer = $CI->output->get_output();

$search = array(
'/\>[^\S ]+/s', //strip whitespaces after tags, except space
'/[^\S ]+\</s', //strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/&lt;!--(.|\s)*?--&gt;/' //strip HTML comments
);
$replace = array(
'>',
'<',
'\\1',
''
);
$buffer = preg_replace($search, $replace, $buffer);

$CI->output->set_output($buffer);
$CI->output->_display();
}
?&gt;

;)
Igor Ferreira Cemim
February 9, 2010
#5
Thank you very much. It helped me a lot.
Luka
July 30, 2010
#6
This messes up my MooTools code pretty badly.
Abdel
August 25, 2010
#7
hey great feature - use php commenting in javascripts to avoid errors though:
&lt;?php // Javascript comment .. bla bla ?&gt;
Anders Moefelt
September 28, 2010
#8
Outputing big amounts of code results on a php memory limit crash. Have you guys figured out a way to prevent this without increasing the memory limit?
Thanks!
Juancho
March 9, 2011
#9
once again another useful post for codeigniter users, thanks
Cipher
June 3, 2011
#10
Good!!, but is not usefull when you set compress_output == TRUE :

$config['compress_output'] = TRUE;
Mow
September 23, 2011
#11
^^
... As for the weight of the generated file, but very useful to obfuscate HTML code
Mow
September 23, 2011
#12
It does not work for the Javascript code.
Anyone has a fix for javascript ???
Danish
November 17, 2011
#13
Fix for inline javacript code:

&lt;?php if (!defined('BASEPATH')) exit('No direct script access allowed');

function compress()
{
$CI =& get_instance();
$buffer = $CI->output->get_output();

$inline_scripts=array();
if (preg_match_all('|([removed]]*?&gt;.*?<\/script>)|is', $buffer, $pock))
{
foreach ($pock[1] as $key=>$content)
{
$inline_scripts['INLINE_SCRIPT_'.$key]=$content;
}
$buffer=str_replace(array_values($inline_scripts), array_keys($inline_scripts), $buffer);
}

$search = array(
'/\>[^\S ]+/s',
'/[^\S ]+\</s',
'/(\s)+/s',
);
$replace = array(
'>',
'<',
'\\1',
);

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

if (count($inline_scripts)>0)
{
$buffer=str_replace(array_keys($inline_scripts), array_values($inline_scripts), $buffer);
}

$CI->output->set_output($buffer);
$CI->output->_display();
}


/* End of file compress.php */
/* Location: ./system/application/hools/compress.php */
Ramil Gallyamow
November 27, 2011
#14
Hi, How can I exclude a certain controlloers or pages from being compressed ?
Amr
April 6, 2012
#15