Design

Implement

Configure

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. <?php
  2. // Start output buffer.
  3. ob_start('compress_page');
  4.  
  5. // html code
  6. ?>
  7.  
  8. <!-- place all your html code here -->
  9.  
  10. <?php
  11. // function to compress page.
  12. function compress_page($buffer) {
  13.     // remove comments, tabs, spaces, newlines, etc.
  14.     $search = array(
  15.         "/ +/" => " ",
  16.         "/<!--(.*?)-->|[\t\r\n]|<!--|-->|\/\/ <!--|\/\/ -->|<!\[CDATA\[|\/\/ \]\]>|\]\]>|\/\/\]\]>|\/\/<!\[CDATA\[/" => ""
  17.     );
  18.     $buffer = preg_replace(array_keys($search), array_values($search), $buffer);
  19.     return $buffer;
  20. }
  21.  
  22. // turn off output buffering and output the page.
  23. ?>

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

warningThis 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.

Ubuntu

Donate

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

Site Specs

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