Skip to content
Advertisement

How to minify php page html output?

I am looking for a php script or class that can minify my php page html output like google page speed does.

How can I do this?

Advertisement

Answer

CSS and Javascript

Consider the following link to minify Javascript/CSS files: https://github.com/mrclay/minify

HTML

Tell Apache to deliver HTML with GZip – this generally reduces the response size by about 70%. (If you use Apache, the module configuring gzip depends on your version: Apache 1.3 uses mod_gzip while Apache 2.x uses mod_deflate.)

Accept-Encoding: gzip, deflate

Content-Encoding: gzip

Use the following snippet to remove white-spaces from the HTML with the help ob_start’s buffer:

<?php

function sanitize_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
        '/<!--(.|s)*?-->/' // Remove HTML comments
    );

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

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

    return $buffer;
}

ob_start("sanitize_output");

?>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement