In this article I'm going to show you how I merge and compress my CSS files using PHP.
Advantages to my method:
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.
<?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(); ?>