How to minify JS in PHP easily...Or something else

Take a look at Assetic, a great asset management library in PHP. It is well integrated with Symfony2 and widely used.

https://github.com/kriswallsmith/assetic


I have used a PHP implementation of JSMin by Douglas Crockford for quite some time. It can be a little risky when concatenating files, as there may be a missing semicolon on the end of a closure.

It'd be a wise idea to cache the minified output and echo what is cached so long as it's newer than the source file.

require 'jsmin.php';

if(filemtime('scripts_template.js') < filemtime('scripts_template.min.js')) {
  read_file('scripts_template.min.js');
} else {
  $output = JSMin::minify(file_get_contents('scripts_template.js'));
  file_put_contents('scripts_template.min.js', $output);
  echo $output;
}

You could also try JShrink. I haven't ever used it before, since I haven't had difficulty with JSMin before, but this code below should do the trick. I hadn't realized this, but JShrink requires PHP 5.3 and namespaces.

require 'JShrink/Minifier.php';

if(filemtime('scripts_template.js') < filemtime('scripts_template.min.js')) {
  read_file('scripts_template.min.js');
} else {
  $output = \JShrink\Minifier::minify(file_get_contents('scripts_template.js'));
  file_put_contents('scripts_template.min.js', $output);
  echo $output;
}