Cookie Consent by Free Privacy Policy Generator

Minify HTML with this PHP function

PHP remove whitespace - Use this handy PHP function to remove all whitespace in HTML pages, effectively minifying the HTML page. This will shave off a few kb's on large HTML pages rendered using PHP.

The snippet features are:

  1. Strip whitespaces after tags, except space
  2. Strip whitespaces before tags, except space
  3. Shorten multiple whitespace sequences
  4. Remove HTML comments
Include the snippet below to one of your global files or add it directly to the HTML pages ending in .php
Code:
<?php    
 function sanitize_output($buffer) {

    $search = array(
        '/\>[^\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;
}

ob_start("sanitize_output");
?>


The snippet above will remove the whitespace on HTML pages. It uses a PHP function to strip out the whitespace between the HTML elements.
 
Back
Top