How to Compress CSS Files Using PHP without Renaming

By Angsuman Chakraborty, Gaea News Network
Monday, January 5, 2009

IF you are using a stylish and feature rich environment for your website, then your CSS files must have reached its limit of annoyance for you. So how can you compress CSS files using PHP? You can. Here is a simple trick to do that. On top of it all when you do it for an existing process, all the older files have to be renamed (CSS files to .php) and thus taking another handful of time and space increasing both the complexities. Keeping that in mind this code won’t ask you to rename the files even. Don’t you wanna know?

Code

< ?php
  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();
? >

Thanks to him for sharing the code with us.

[p.s. - Ignore the space between < ? and ? > in the original program]

Discussion
July 21, 2010: 10:50 am

Everything is available on taragana. Cut, Copy and Paste does not take much time.

April 5, 2010: 9:41 am

That is well known that cash makes people autonomous. But what to do if somebody doesn’t have money? The only one way is to get the home loans or collateral loan.

November 27, 2009: 2:28 am

This is a great help but where do I put this code?

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :