DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Chara has posted 50 posts at DZone. View Full User Profile

Compress multiple CSS files

02.12.2013
| 3600 views |
  • submit to reddit
<?php
// source : http://www.apphp.com/index.php?snippet=php-compress-multiple-css-files
header('Content-type: text/css');
ob_start('compress_css');
 
function compress_css($buffer) {
  /* remove comments in css file */
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  /* also remove tabs, spaces, newlines, etc. */
  $buffer = str_replace(array("\r", "\n", "\r\n", "\t", '  ', '    ', '    '), '', $buffer);
  return $buffer;
}
 
/* a list of your css files */
include('style.css');
include('css/menu.css');
include('css/typography.css');
include('css/print.css');
include('inc/css/footer.css');
 
ob_end_flush();
?>

  Usually when you're using different CSS files on your site, they might take a quite long to be loadedload. Using this PHP code, you can compress them into a single file with no unnecessary white spaces or comments. Why we need to compress multiple CSS files? The answer is: the compressing procedure may take a less time than a total time of loading each file separately.