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.

December 11th, 2007 at 7:17 am

Calculating the V.A.T. amount from the total price

Sometimes you need to calculate the V.A.T. (for Germans: MwSt.) from a given total price. This is, for example, if you charge an arbitrary total price, but need to display the V.A.T. percentage along with the V.A.T. amount. For this purpose, you can use the following code:

PHP:
  1. <?php
  2.    
  3.     function calc_vat_amount_from_total($total, $vat)
  4.     {
  5.         $total = (float)$total;
  6.         $vat = (float)$vat;
  7.  
  8.         if (!$total || !$vat) return false;
  9.  
  10.         $net = $total / (float)('1.'.$vat);
  11.         $vatAmount = $total - $net;
  12.  
  13.         return sprintf("%01.2f", $vatAmount);
  14.     }
  15.  
  16.     $total = '35.00'; // It's a string, but could also be a float or int.
  17.     $vat = '19'; // dito
  18.  
  19.     $vat_amount = calc_vat_amount_from_total($total, $vat);
  20.     echo "The ticket fare of $total &#8364; contains $vat% V.A.T. ($vat_amount &#8364;).";
  21.  
  22. ?>