Premium Wordpress Themes

Advertisement

Combine Your CSS Files with PHP

Posted on Monday, September 28th, 2009 at 9:31 am

I like to work with multiple CSS files. I also like to limit the number of HTTP request my site/app is making.

I’ve seen a couple methods on the Internet of using PHP to combine your files and decided to use some of those methods in my own little script.

Basically this script lives in your CSS folder. It grabs every file, opens it up, takes the content and then mashes it all together. It also takes our new content and strips any comment and white space to create a new compressed file.

//This file takes all the .css files in the css folder and puts them into 1 big file
//It cuts down on HTTP requests

$dir = opendir('./');
$css = '';

while($read = readdir($dir))
{

	//garbage left over
	if($read != '.' && $read != '..'){

		//don't include this file
		if($read != 'master.php'){

			//open and merge
			$fileHandle = fopen($read, 'r');

			if(filesize($read) > 0){

				$css .= "\n" . fread($fileHandle, filesize($read));
				fclose($fileHandle);

			}

		}

	}

}

closedir($dir); 

header("Content-type: text/css");

//Lets compress the css file

// remove comments
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
// remove tabs, spaces, newlines, etc.
$css = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $css);

echo $css;

To use this file in your HTML template, just reference the script.


I’m always looking for a more optimized way of doing things, so if you can see any way to improve on this script, please let me know!

I’ve tried to find the original site that inspired this script, but I can’t seem to find it. If anyone knows or see’s a script like this around the internet please let me know so I can credit the inspiration.

Share these links, you kinda have to!
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Twitter

|