A Simple Minifier for PHP Sites

Created by: :: Apr 11, 2016 6:11:15 PM PDT (Revised Sep 25, 2016 9:51:29 AM PDT)

Minify your HTML in 4 simple regular expressions

For those of you looking to improve your SEO optimization, a key factor in rendering HTML quickly is to ensure your HTML output is minified properly. This means getting your HTML output onto one line and eliminating unnecessary whitespace and comments throughout the HTML itself.

If your site is written in PHP, this is relatively easy. You can write a method that takes the output and echos out some preg_replaced() items to help minify your code.

Class file: Minify.class.php

<?php

/*** line by line ... ***/

function html($input)
{

    // newlines and tabs
    $output = preg_replace("~\n|\r|\t~", ' ', $input);

    // extra spaces
    $output = preg_replace("~\s{2,}~", ' ', $output);

    // space between tags
    $output = preg_replace("~>\s<~", '><', $output);

    // html comments
    $output = preg_replace("~<!--.*?-->~", null, $output);

    return $output;

}


/*** ... OR by array with keys ***/

function html($input)
{

    $find_replace = array(
        '~\n|\r|\t~' => ' ',
        '~\s{2,}~' => ' ',
        '~>\s<~' => '><',
        '~<!--.*?-->~' => null,
    );

    $find = array_keys($find_replace);
    $replace = $find_replace;

    return preg_replace($find, $replace, $input); // output

}



Since all my output is echoed from a single variable, I only need to apply this once.

<?php

    // output page here

    echo \View\Html\Minify::html($my_entire_page);



However, if you've "included" or "required" other content (such as the header, or some HTML pieces) which have already been output by "echo" or simply exist as HTML, you can wrap it in an output buffer

<?php

    // header
    ob_start();
    require('header.php');
    $header = ob_get_clean();

    // body
    $rest_of_page = '<div>body of page goes here</div>';

    // footer
    ob_start();
    require('footer.php');
    $footer = ob_get_clean();

    // echoing it all out to one line of HTML
    echo \View\Html\Minify::html($header);
    echo \View\Html\Minify::html($rest_of_page);
    echo \View\Html\Minify::html($footer);

    // or, of course.... echo \View\Html\Minify::html($header . $rest_of_page . $footer);


Reply

Replies:

  • guest Jun 15, 2016 10:12:25 PM PDT
    Does this work for really large web pages? What is the performance impact?
    Reply
    • josh Jun 15, 2016 11:57:04 PM PDT
      So far yes. I've used this on profile pages that have essays of html embedded profile text, videos, page snippets and more. Even in extreme cases, there was no notable impact on performance (the entire page rendered in less than 200ms).
      Reply