Compress CSS With PHP Without Renaming The CSS Files

I was actually looking for an easy way to compress css files using PHP for one of my static websites. It is a known fact that PHP can be used to compress CSS files which therefore improves the overall page performance and loading time. However most methods require that you rename your css file to php and others require that you modify your htaccess file. I was looking for a cleaner way when I came across the Reinhold Weber method on CatsWhoCode.

Find below a sample usage of the Reinhold Weber method to compress an unlimited amount of css files without renaming to php. The code will even clean your css files of comments lines which is simply awesome.

<?php
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("rn", "r", "n", "t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}

/* your css files */
include('style.css');
include('red.css');
include('blue.css');
include('typo.css');

ob_end_flush();
?>

Divi WordPress Theme

Leave a Reply

Be the First to Comment!

Leave a Reply


wpDiscuz