Minify HTML in Codeigniter using Hooks

0
1665
Compress HTML in CodeIgniter using Hooks

HTML Minification is the removal of unnecessary characters and lines in HTML code. Indentation, comments, empty lines, etc. are not required while rendering in HTML. Trimming these details can save download file size not only without affecting the output but also improving the performance.

CodeIgniter

CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications. CodeIgniter is loosely based on the popular model–view–controller (MVC) development pattern.

In this post, we will learn how to minify HTML content in Codeigniter using Hooks.

1. Enable Hooks in Config

$config['enable_hooks'] = TRUE;

2. Declare a Hook in hooks.php

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

3. Add the hook

Create a file application/hooks/compress.php with the following code in it:

<?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 */

That’s it ! Now the HTML rendered with be minified in the webpage.

Refer this video for full guidance :

ALSO READ  Get Geo Location Details of Client using PHP

Comments are closed.