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

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(

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

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

    //replace style elements
        //minify the css
        $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>';

    //replace script elements
        $minifiedCode = JSMin::minify($matches[1]);
        return '<script>'.$minifiedCode.'</script>';

    return $buffer;

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 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *