Minify or Compress HTML Output with CodeIgniter

by heru on December 23, 2010

In web design, it is important that you minify or compress your HTML web page for a faster load. Google Page Speed includes “Minify HTML” as one of the factors that contribute to a fast loading web page.

Fortunately, you can do this easily with CodeIgniter using Hooks. Learn more about CodeIgniter Hooks.

In order to minify HTML output, we need to do the following steps:

  1. Enable hook on CodeIgniter:
    - Open up /system/application/config/config.php.
    - Set $config['enable_hooks'] = TRUE;
  2. Create a hook file with the minify HTML:
    - Create a file Minifyhtml.php in /system/application/hooks/ folder.
    - Copy paste the following code:
    <?
    class Minifyhtml {
    function output()
    {
    $CI =& get_instance();
    $buffer = $CI->output->get_output();$search = array(
    '/\>[^\S ]+/s', //strip whitespaces after tags, except space
    '/[^\S ]+\',
    '<', '\\1' );
    $buffer = preg_replace($search, $replace, $buffer); $CI->output->set_output($buffer);
    $CI->output->_display();
    }
    }
    ?>

    Thanks to Jerome Jaglale at CodeIgniter Wiki for the Minify HTML code.
  3. Setup your hook config file found at /system/application/config/hooks.php and enter the following code:

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

    The above code basically tells CodeIgniter to do a different thing for the display_override (which is the hook to display the output). The code will tell CodeIgniter to find a file name called Minifyhtml.php in the folder /system/application/hooks/, find a class Minifyhtml and run the function output() as a substitute when running the display_override. Thus, it basically replaces the output with the minifyhtml function that we have created which takes in the output and produces the minified version.

There you go. A simple 5 minutes step that will help alot. Plus, if you don’t want to see the “minified” version of your HTML, you can simply turn the “hook” off in the config file. :)

Related Posts

  • No Related Post
  • Abc

    php displays an error for search array item: \1
    What should I do about that?

  • Thomas Daugaard

    This can cause problems for elements like in certain cases where a line break is significant to the browser and causes rendering to be different in some browsers.

    Removing leading white-spaces only seems to be OK.

    • Heru Setiawan

      Yes, I believe it will cause that problem on certain browser. Maybe, we can resolve this by fully dependent on the css file instead?

Previous post:

Next post: