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/hooks/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
Aug 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
Sep 18, 2009
#2
are there any benchmarks to show how effective this step is? or does this exist more for code obfuscation?
matt
Nov 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
Feb 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
Feb 9, 2010
#5
Thank you very much. It helped me a lot.
Luka
Jul 30, 2010
#6
This messes up my MooTools code pretty badly.
Abdel
Aug 25, 2010
#7
hey great feature - use php commenting in javascripts to avoid errors though:
&lt;?php // Javascript comment .. bla bla ?&gt;
Anders Moefelt
Sep 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
Mar 9, 2011
#9
once again another useful post for codeigniter users, thanks
Cipher
Jun 3, 2011
#10
Good!!, but is not usefull when you set compress_output == TRUE :

$config['compress_output'] = TRUE;
Mow
Sep 23, 2011
#11
^^
... As for the weight of the generated file, but very useful to obfuscate HTML code
Mow
Sep 23, 2011
#12
It does not work for the Javascript code.
Anyone has a fix for javascript ???
Danish
Nov 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
Nov 27, 2011
#14
Hi, How can I exclude a certain controlloers or pages from being compressed ?
Amr
Apr 6, 2012
#15
Check this out https://github.com/johngerome/CodeIgniter-Minifyhtml-hooks#codeigniter-minifyhtml-hooks. It works Perfectly!
CodeIgniter Geeks
Sep 6, 2013
#16
Thanks for the code!!
Paulo H. Alves
Mar 5, 2014
#17