Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Last active June 17, 2019 14:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilemuller/4585164 to your computer and use it in GitHub Desktop.
Save cecilemuller/4585164 to your computer and use it in GitHub Desktop.
PHP function to minify JavaScript code using Google Closure Compiler
<?php
/**
* Minifies JavaScript code using Google Closure Compiler.
*
* @param String $code
* JavaScript code to reduce
*
* @param String $level
* Type of compression of the code.
* Valid values are: "WHITESPACE_ONLY", "SIMPLE_OPTIMIZATIONS" and "ADVANCED_OPTIMIZATIONS".
*
* @return String
* The minified equivalent (or the same code if there was a problem accessing the webservice)
*
* @see Closure compilation levels
* https://developers.google.com/closure/compiler/docs/compilation_levels
*
*/
function minify_javascript($code, $level = 'SIMPLE_OPTIMIZATIONS'){
try {
$ch = curl_init('http://closure-compiler.appspot.com/compile');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'output_info=compiled_code&output_format=text&compilation_level=' . $level . '&js_code=' . urlencode($code));
$minified = curl_exec($ch);
curl_close($ch);
} catch (Exception $e) {
$minified = $code;
}
return $minified;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment