Last active
June 17, 2019 14:48
-
-
Save cecilemuller/4585164 to your computer and use it in GitHub Desktop.
PHP function to minify JavaScript code using Google Closure Compiler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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