Return to Snippet

Revision: 62463
at February 25, 2013 18:46 by apphp-snippets


Initial Code
<?php
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", "
", "\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();
?>

Initial URL
http://www.apphp.com/index.php?snippet=php-compress-multiple-css-files

Initial Description
Usually when you're using different CSS files on your site, they might take a quite long to be loaded. 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.

Initial Title
Compress multiple CSS files

Initial Tags
css, php

Initial Language
PHP