Minify/Compress CSS using PHP
Google recently announced that site speed may be the next ranking factor. With this in mind I am going to explain how to minify/compress your CSS files using PHP. Many site use a few different CSS files to format their website, each one of these files requires a HTTP requests which an slow things down.
First you will need to create a new php file that will act as a CSS files when it is called.
header('Content-type: text/css');
// Since the documents is Static I set a future date to expire.
header("Expires: Thu, 15 Apr 2012 20:00:00 GMT");
Now that you have your PHP document setup you need to create a function that will minify your current CSS files. Minifying your CSS basically means to remove all unnecessary whitespace and symbols. The function below will do that nicely.
$css = preg_replace( '#\s+#', ' ', $css );
$css = preg_replace( '#/\*.*?\*/#s', '', $css );
$css = str_replace( '; ', ';', $css );
$css = str_replace( ': ', ':', $css );
$css = str_replace( ' {', '{', $css );
$css = str_replace( '{ ', '{', $css );
$css = str_replace( ', ', ',', $css );
$css = str_replace( '} ', '}', $css );
$css = str_replace( ';}', '}', $css );
return trim( $css );
}
Now that you have your function to minify your CSS you must call your CSS files and have them minified. The code below will get the contents of the CSS file, minify it, and display it to the browser.
$file = 'text.css';
$content = @file_get_contents( $file );
echo minify( $content );
//Repeat those three lines of code for each CSS file
Minifying your CSS file is complete. Now to compress the file using GZip.
A the beginning of your same PHP file, you need to add this line of code.
At the end of your PHP file you need to add this line of code and you are complete.
Now in your main HTML file you need to reference the new PHP file we just created.
<link href="/FILENAME.PHP" rel="stylesheet" type="text/css" media="all" />
It may seem weird to link to a PHP files and say it’s a CSS file but in the first bit of code we wrote, we told the browser that it is a CSS file regardless of the extension.
Using this method on my website I was able to reduce my load time from 2.6 second to 1.46 second, an increase of 46%! Think about what it can do to your website!
Feel free to ask questions in the comments below.