How to Compress HTML Code using PHP

Compressing the code is very beneficial for a website it increases website performance and load it faster by making webpage smaller and lighter and it also affects website SEO, so this script strips out all the line breaks and spaces in your code and puts it on one line, compressing your code and making it faster.

PHP and HTML Code

<?php
ob_start("compress_code");

function compress_code($code) {
    $search = array(
        '/\>[^\S ]+/s',
        '/[^\S ]+\</s',
        '/(\s)+/s'
    );

    $replace = array('>', '<', '\\1');
    $code = preg_replace($search, $replace, $code);
    return $code;
}
?>
<html>
    <body>
        <p>How to Compress HTML Code using PHP</p>
    </body>
</html>

<?php
ob_end_flush();
?>

Leave a Reply

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