Efficient techniques to compress css files in php

Efficient techniques to compress css files in php

Today I am going to share 3 most efficient techniques to compress CSS files using PHP. All of them are working great for any application. You know, for a complex design we need to write thousands line of CSS script and CSS files need to load fast for displaying website interface properly. Large CSS file takes more time to load, but we can easily solve this using PHP. So, lets see compressing techniques –

Technique 01:

ob_start ("ob_gzhandler");
header ("content-type: text/css; charset: UTF-8");
header ("cache-control: must-revalidate");
$offset = 60 * 60;
$expire ="expires: ".gmdate ("D, d M Y H:i:s", time() + $offset)." GMT";
header ($expire);

Technique 02:

This technique remove all unnecessary space, new line from your css script. In this way it save few bytes of CSS file and file loaded fast than normal load.

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

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;
}

/*Your css files*/
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');

ob_end_flush();

Technique 03:

Most common and super simple techniques for beginner. Create a style.css. PHP file and write following codes in there.

if(extension_loaded('zlib')){ob_start('ob_gzhandler');} header("Content-type: text/css");
if(extension_loaded('zlib')){ob_end_flush();}

Enjoy!

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top