Compress multiple CSS files


/ Published in: PHP
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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", "
  10. ", "\t", ' ', ' ', ' '), '', $buffer);
  11. return $buffer;
  12. }
  13.  
  14. /* a list of your css files */
  15. include('style.css');
  16. include('css/menu.css');
  17. include('css/typography.css');
  18. include('css/print.css');
  19. include('inc/css/footer.css');
  20.  
  21. ?>

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.