Google Closure Compiler with PHP
Today Google released their new Closure Compiler, you can use it to optimize and minify your javascripts.
UPDATE: Use Google Closure Compiler Local with PHP (Command Line)
Now i show you how to use the new Google Closure Compiler over the RESTful API with PHP5. First of all, you don’t need to install anything, we will connect the free API via cURL usually activated in PHP5.
The API (see reference) resides under the following URL and requires four params:
http://closure-compiler.appspot.com/compile
compilation_level is one of three options: WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS, i use simple optimizations, it don't need further config (like advanced) but is better than whitespace only. output_format is "text" if you want compile a javascript output_info is "compiled_code" if you want compile a javascript js_code is your javascript source code, instead you can submit "code_url" param, an url to a javascript-file
enough with theory, now the PHP code:
$script = file_get_contents('http://www.domain.com/scripts/script.js'); $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=SIMPLE_OPTIMIZATIONS&js_code=' . urlencode($script)); $output = curl_exec($ch); curl_close($ch);
i use it in a deployer script and replace the content of my script files with the compiled versions. you can tryout the compiler with a simple html-form.
Tags: closure, closure compiler, curl, Google, javascript, PHP