How to minify view HTML in Codeigniter 4 (CI 4)

Solution 1:

In CodeIgniter4 You can use Events to Minify the output (Instead of using Hooks like what we did in CodeIgniter3) , by adding the following code inti app/Config/Events.php file

//minify html output on codeigniter 4 in production environment
Events::on('post_controller_constructor', function () {

  if (ENVIRONMENT !== 'testing') {
while (ob_get_level() > 0)
{
    ob_end_flush();
}

ob_start(function ($buffer) {
    $search = array(
        '/\n/',      // replace end of line by a <del>space</del> nothing , if you want space make it down ' ' instead of ''
        '/\>[^\S ]+/s',    // strip whitespaces after tags, except space
        '/[^\S ]+\</s',    // strip whitespaces before tags, except space
        '/(\s)+/s',    // shorten multiple whitespace sequences
        '/<!--(.|\s)*?-->/' //remove HTML comments
    );

    $replace = array(
        '',
        '>',
        '<',
        '\\1',
        ''
    );

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

  }

});

see https://gitlab.irbidnet.com/-/snippets/3

Solution 2:

You need the extend your core system classes to be able to do that in a system wide scope.

Every time CodeIgniter runs there are several base classes that are initialized automatically as part of the core framework. It is possible, however, to swap any of the core system classes with your own version or even just extend the core versions.

Two of the classes that you can extend are these two:

  • CodeIgniter\View\View
  • CodeIgniter\View\Escaper

For example, if you have a new App\Libraries\View class that you would like to use in place of the core system class, you would create your class like this:

The class declaration must extend the parent class.

<?php namespace App\Libraries;

use CodeIgniter\View\View as View;

class View implements View
{
     public function __construct()
     {
         parent::__construct();
     }
}

Any functions in your class that are named identically to the methods in the parent class will be used instead of the native ones (this is known as “method overriding”). This allows you to substantially alter the CodeIgniter core.

So in this case you can look at your system view class and just change it to return the output already compressed.

In your case You might even add an extra param so that the view function can return the output either compressed or not.

For more information about extending core classes in CodeIgniter 4 read this:

https://codeigniter.com/user_guide/extending/core_classes.html#extending-core-classes