Compress HTML
Thursday, 20 August 2009 07:41 AM

Compressing your HTML page using PHP

Compressing a HTML page in php in very simple to implement especially if you use a content management system for your website.

PHP CODE:

 

Compress HTML
  1. // Start output buffer.
  2. ob_start('compress_page');
  3.  
  4. // html code
  5. ?>
  6.  
  7.  
  8. // function to compress page.
  9. function compress_page($buffer) {
  10.     // remove comments, tabs, spaces, newlines, etc.
  11.     $search = array(
  12.         "/ +/" => " ",
  13.         "/|[\t\r\n]||\/\/ ||\]\]>|\/\/\]\]>|\/\/ => ""
  14.     );
  15.     $buffer = preg_replace(array_keys($search), array_values($search), $buffer);
  16.     return $buffer;
  17. }
  18.  
  19. // turn off output buffering and output the page.
  20. ?>

And that's it at it's very basic!

This function will not compress commented JavaScript, it will compress the JavaScript that's not commented. For JavaScript compression it is best to serve the JavaScript from external files and compressed with either JavaScriptPacker.php or YUI compressor. CSS compression can be further done with another compression function and I will show this in another tutorial.

Last Updated ( Tuesday, 17 May 2011 12:25 PM )

Contacts

If you would like to contact me regarding the range of serves that I can offer. Please use the details below.
Office: 01767 631679
email: Shaun Freeman

Ubuntu

Donate

If you find this website useful and you would like to contribute feel free to by using the button below.

Links

Web Design - A list of website designers in Bedfordshire.

Site Specs

Site best viewed in a screen resolution of 1024x768 & 32 bit colours or higher using the latest version of Firefox