December 18th, 2007 at 10:07 am

Improve loading speed of webpages by compressing HTML

Here's a simple HTML "compressor" in PHP, which will reduce the size of HTML served to the client by 10 to 20 percent, depending on your indentation style and commenting. If many of your readers have lousy bandwidth, the slight overhead of this method is worth it.

PHP:
  1. <?php
  2.     function compress($content)
  3.     {
  4.         $content = preg_replace('/[\n\t\s]+/s', ' ', $content);
  5.         $content = preg_replace('/<!--.*?-->/s', '', $content);
  6.         return $content;
  7.     }
  8.  
  9.     ob_start();
  10.     require "/var/www/htdocs/somefile.php";
  11.     $content = ob_get_contents();
  12.     ob_end_clean();
  13.  
  14.     echo compress($content);
  15. ?>

By the way, if you have a rather hungry dynamic application (e.g. WordPress with certain plugins) on a rather weak server, consider using a caching solution like 1 Blog Cacher, so you don't have to regenerate the pages everytime somebody retrieves them. And, of course, consider using output gzip compression -- be it via webserver modules such as mod_gzip/mod_deflate or based on your web application.