Posted By

apphp-snippets on 02/25/13


Tagged

css php compress


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

AymanKRady
gecube
3wil


Compress multiple CSS files


 / Published in: PHP
 

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

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.

  1. <?php
  2. header('Content-type: text/css');
  3. ob_start('compress_css');
  4.  
  5. function compress_css($buffer) {
  6. /* remove comments in css file */
  7. $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  8. /* also remove tabs, spaces, newlines, etc. */
  9. $buffer = str_replace(array("\r", "\n", "\r\n", "\t", ' ', ' ', ' '), '', $buffer);
  10. return $buffer;
  11. }
  12.  
  13. /* a list of your css files */
  14. include('style.css');
  15. include('css/menu.css');
  16. include('css/typography.css');
  17. include('css/print.css');
  18. include('inc/css/footer.css');
  19.  
  20. ?>

Report this snippet  

You need to login to post a comment.