In this article I'm going to show you how I merge and compress my CSS files using PHP.

Please note this article is on my todo list to update. Preprocessors make this work easy.

Advantages to my method:

  • Size of the CSS - No comments, no spaces no line returns
  • Reduction of http requests - The browser doesn't have to talk to the server to download multiple files.
  • Keep your CSS files organised - You keep the ability to change and modify your existing files.

Previously I mentioned at process.php. I substitute this file for that and place all my CSS which requires PHP here.

The process is simple, take the file below and place it into your CSS directory. Modify the names of your style sheet near the bottom of the below file, and you are all set.

The Code

<?php
/** 
* Author: Nick Yeoman
* process.php
* v1.0
* Last Updated June 7, 2011
* Documentation: http://www.nickyeoman.com/blog/css/57-css-php
**/

// initialize ob_gzhandler to send and compress data
ob_start ("ob_gzhandler");

// required header info and character set
header("Content-type: text/css;charset: UTF-8");

// duration of cached content (24 hours)
$offset = 60 * 60 * 24;

// cache control to process
header ('Cache-Control: max-age=' . $offset . ', must-revalidate');

// expiration header format
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s",time() + $offset) . " GMT";

// send cache expiration header to browser
header($ExpStr);

// initialize compress function for white-space removal
ob_start("compress");

// Begin function compress
function compress($buffer) {

// remove comments
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);

// remove tabs, spaces, new lines, etc. 
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);

// remove unnecessary spaces
    $buffer = str_replace('{ ', '{', $buffer);
    $buffer = str_replace(' }', '}', $buffer);
    $buffer = str_replace('; ', ';', $buffer);
    $buffer = str_replace(', ', ',', $buffer);
    $buffer = str_replace(' {', '{', $buffer);
    $buffer = str_replace('} ', '}', $buffer);
    $buffer = str_replace(': ', ':', $buffer);
    $buffer = str_replace(' ,', ',', $buffer);
    $buffer = str_replace(' ;', ';', $buffer);
return $buffer;
}

/**
INCLUDE YOUR STYLE SHEETS HERE
**/
require_once('reset.css');
require_once('html.css');
require_once('library.css');
require_once('template.css');

// end compression
ob_end_flush();

?>