Compressing your HTML page using PHP

Compressing your HTML page using PHP

Compressing a HTML page in php in very simple to implement especially if you use a content management system for your website.

<?php     
    // Start output buffer.
    ob_start('compress_page');
    // html code

    place all your html code here

<?php     
    // function to compress page.     
    function compress_page($buffer) {         
        // remove comments, tabs, spaces, newlines, etc.         
        $search = array(             
            "/ +/" => " ",
            "/|[\t\r\n]||\/\/ ||\]\]>|\/\/\]\]>|\/\/" => ""
        );
        $buffer = preg_replace(array_keys($search), array_values($search), $buffer);
        return $buffer;
    }

    // turn off output buffering and output the page.
    ob_end_flush();
?>

And that's it at it's very basic!

warning This function will not compress commented JavaScript, it will compress the JavaScript that's not commented. For JavaScript compression it is best to serve the JavaScript from external files and compressed with either JavaScriptPacker.php or YUI compressor. CSS compression can be further done with another compression function and I will show this in another tutorial.



13/04/2014 12:44:00 Shaun Freeman Filed Under: PHP PHP

Twitter Feed
Shaun Freeman @Zendmaster

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/lSFWmpHTX1 Patrick Stewart talks about meeting Sting on the set of DUNE (Funny to the EXTREME)

Shaun Freeman @Zendmaster

I added a video to a @YouTube playlist https://t.co/pmXSmod4ti Anonymous - This will Change Everything You Know... (2018-2019)

Shaun Freeman @Zendmaster

I added a video to a @YouTube playlist https://t.co/GkwTCvBfes Will Artificial Intelligence Take Over The World?

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/Y1ulafmsC6 Frank Abagnale: "Catch Me If You Can" | Talks at Google

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/NBdW2xFnqD ETS2: Special Transport DLC Trailer