Clean your HTML output

By Julien Perez (T0aD)
Sometimes you'd like to clean your HTML output to remove useless stuff that may slow down the loading of your page. Here is a little trick to slim your website output ;)
Let's say we want to remove comments, lines separator (that can affect the loading of your page) and blank spaces. All we have to do is to collect all the output returned by cake, modify it and return it in the afterFilter hook in the app_controller.php file:

Controller Class:

Download code <?php 

class AppController extends Controller
{
    function 
beforeRender()
    {
        if (
Configure::read('debug') == 0) {
            
ob_start();
        }
    }

    function 
afterFilter()
    {
        if (
Configure::read('debug') == 0) {
            
$output ob_get_contents();
            
ob_end_clean();
            echo 
$this->_clean($output);
        }
    }

    function 
_clean($string)
    {
        
$string str_replace("\n"''$string);
        
$string str_replace("\t"''$string);
        
$string preg_replace('/[ ]+/'' '$string);
        
$string preg_replace('/<!--[^-]*-->/'''$string);
        return 
$string;
    }
}
?>

You can check out the results on my website http://www.lescigales.org, enjoy ;)

 

Comments 681

CakePHP Team Comments Author Comments
 

Comment

1 Nice Idea but

Nice use of the afterRender() callback, but if you have the PHP Tidy extension loaded on your server, you can make use of it and output clean, nested and semantic HTML with http://bakery.cakephp.org/articles/view/tidy-output-filtering.

Also, as for increasing performance, I would have thought that running the entire output through 2 preg_replace()'s would actually slow things down a bit (unless CakePHP is caching the output - did you try benching this?)
Posted Jun 15, 2008 by Jonny Reeves
 

Comment

2 Nice Idea but

Nice use of the afterRender() callback, but if you have the PHP Tidy extension loaded on your server, you can make use of it and output clean, nested and semantic HTML with http://bakery.cakephp.org/articles/view/tidy-output-filtering.

Also, as for increasing performance, I would have thought that running the entire output through 2 preg_replace()'s would actually slow things down a bit (unless CakePHP is caching the output - did you try benching this?)

No I didn't benchmark these 2 preg_replace() as Im not focused on micro-optimization and as this article was more about the functionality first :)

Some time ago someone suggested me a more elegant way to achieve this, with a component I believe.

Thanks for your comment !
Posted Jun 22, 2008 by Julien Perez