Back To Normal
Click Here To Subscribe Via Email

Subscribe To Our E-Mail Newsletter

Wednesday, November 19, 2014

Minify HTML, CSS and Javascript on the fly using PHP


Couch ModePrint It



Last night, I was optimizing a web-app that is powered by PHP. There was lack of time and many inline javascript and css codes that were needed to be minified.

I decided to use PHP's output buffering for minifying HTML output along with inline javascript and css.  So, i wrote some simple lines of code and it was achieved easily. I thought this code will be useful for many webmasters, so i am sharing it here :)


The code is simple. It strips extra characters from HTML and CSS. Javascript minification is done here by using JSMin. So, you must get it here.


Place this code on the top of your PHP file (or a global header file that is included in all other files -- was header.php in my case). Don't forget to have JSMin.php in the same directory as we are using that file for javascript minification.

PHP Code for Minification


require_once("JSMin.php"); 
function minify_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
    );

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

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

    //replaces
    $buffer=str_replace(" type=\"text/javascript\"", "", $buffer);
    $buffer=str_replace(" type=\"text/css\"", "", $buffer);

    
    //replace style elements
    $buffer=preg_replace_callback("/<style>([\s\S]*?)<\/style>/",function($matches){
        //minify the css
        $css=$matches[1];
        $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
    
        $css = str_replace(array("\r\n","\r","\n","\t",'  ','    ','     '), '', $css);
    
        $css = preg_replace(array('(( )+{)','({( )+)'), '{', $css);
        $css = preg_replace(array('(( )+})','(}( )+)','(;( )*})'), '}', $css);
        $css = preg_replace(array('(;( )+)','(( )+;)'), ';', $css);

        return '<style>'.$css.'</style>';
    },$buffer);

    
    //replace script elements
    $buffer=preg_replace_callback("/<script>([\s\S]*?)<\/script>/",function($matches){
        $minifiedCode = JSMin::minify($matches[1]);
        return '<script>'.$minifiedCode.'</script>';
    },$buffer);


    return $buffer;
}
ob_start("minify_output");



This code will work good unless you have something different as expected in your generated html. This code expects <script> and <style> tags for inline javascript and css. You can have type="text/javascript" or type="text/css" in these tags but no other attribute. (If so, you can adjust the php code to handle that.)

Have fun coding :)



:D
:)
:[
;)
:D
:O
(6)
(A)
:'(
:|
:o)
8)
(K)
(M)