PHP CSS Compressor

Thursday, August 24, 2006 by Nicholas Gagne

Compressing CSS is a great way to save some bandwidth, especially on more complex sites with stylesheets reaching more than 1000 lines of code. There are many websites out there that will compress your stylesheets for you, but the problem is maintaining them afterwards. Either search through a cryptic block of code, or keep backups and recompress after every change. While you might save file size, you'll probably lose development time.

In order to solve this problem I've come up with a few lines of code you can include in your css stylesheets that will automatically handle compression for you.

Here's how it works:

  • The user's browser requests the stylesheet as usual
  • The server compresses the stylesheet using PHP
  • The stylesheet is outputted to the browser

All of this happens without the user ever realizing it. Best of all, it doesn't change your CSS stylesheet, allowing you to easily maintain and update it.

First, add this code to the very top of your css stylesheet:

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

The first line let's the browser know that this is a CSS stylesheet. Next, it starts the overflow buffer collection for later processing with the "compress" function. The compress function is used to remove all comments and spacing. Finally, the compressed CSS is sent to the browser.

Next, add this code to the very bottom of your CSS stylesheet:

<?php ob_end_flush();?>

Basically, this tells PHP to stop collecting output, and to run the previously specified "compress" function. After that, the compressed CSS stylesheet is sent to the browser. You can download the PHP CSS Compressor Template file with the required PHP code included to get started quick.

If you want to reference the file using a file name such as "screen.css" and have the PHP code parsed, you could use SetHandler in your .htaccess file like this:

<Files screen.css>
  SetHandler  application/x-httpd-php 

I hope this will help you, your friends, your colleagues, and your brother's cat "Fluffy" to easily maintain compressed CSS.