Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Speeding Up Your PHP Web Site

Minify Your CSS, JavaScript and HTML

An extremely effective way to decrease the amount of traffic being sent is to make your JavaScript and CSS files smaller. One way to do this is to use Yahoo!'s YUI Compressor.

Although this is a Java library, it is easy to leverage it from within PHP. All you need is Java installed (which most servers do) and the yuicompressor.jar file.

The following code shows a basic implementation of using YUI Compressor to serve minified JavaScript.

Listing 1 Compressing JavaScript and CSS with YUI Compressor (listing-1.php)
    $java = '/usr/bin/java';
    $yui  = '/path/to/yuicompressor.jar';
    $file = '/path/to/script.js';
    $cmd = sprintf(
        '%s -jar %s --type js %s',
    $output = trim(`$cmd`);
    header('Content-type: text/javascript');
    header('Content-length: ' . strlen($output));
    echo $output;

It is strongly recommended that you cache output from YUI Compressor, since minifying in real-time can be slow and resource-intensive.

When using YUI Compressor, you can either specify the content type (either js or css), or it will auto-detect based on the input filename.

You can achieve similar results for your HTML files using the htmlcompressor tool. Once again, this is a Java library. This library will automatically use YUI Compressor if you use it for CSS or JavaScript (as long as yuicompressor.jar is present in the same directory as htmlcompressor.jar).

In This Article