Merge and minify CSS files with PHP

11th Apr, 2011 | php web

This looks like good potential code to use in a phing plugin, or during a Sculpin production site build.

  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("rn", "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();

it looks like there are more powerful libraries to handle this task, such as [https://github.com/matthiasmullie/minify/blob/master/README.md]

Ultimately it seems nodejs is the way to go for optimum css/js proessing but this small bit of code looks fine for a simple php only solution.