Compress Your XHTML Page Output Using PHP Output Buffers

By  on  

Us programmers love to keep our code readable and neat, which is why we use hundreds of tabs and line feeds in our code. The problem with doing this in the web programming world is that our users don't care about our neatly indented code. They don't care about our detailed code comments. They certainly don't care about the two-vs-three-vs-four spaces in a tab debate. So why should we make them download the extra code? With some quick PHP code, you don't need to.

The PHP Code

The entire system works on some really short PHP code:

<?php
	/*  start the output buffer  */
	ob_start('compress_page');

	/*  xhtml code below  */
?>
<!-- all xhtml content here -->
<?php
	/*  end the buffer, echo the page content  */
	ob_end_flush();

	/*  function that gets rid of tabs, line breaks, and extra spaces  */
	function compress_page($buffer) {
		$search = array('/>[^S ]+/s', '/[^S ]+</s', '/(s)+/s');
		$replace = array('>', '<', '1');
		return preg_replace($search, $replace, $buffer);
	}
?>

That's it. Compressing your page is easy to implement, especially if you use an MVC system for your website.

Recent Features

  • By
    Animated 3D Flipping Menu with CSS

    CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more.  I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...

  • By
    Regular Expressions for the Rest of Us

    Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

Incredible Demos

  • By
    MooTools dwCheckboxes Plugin

    Update / Fix: The checkboxes will no longer toggle when the "mouseup" event doesn't occur on a checkbox. Every morning I wake up to a bunch of emails in my Gmail inbox that I delete without reading. I end up clicking so many damn checkboxes...

  • By
    HTML5 Datalist

    One of the most used JavaScript widgets over the past decade has been the text box autocomplete widget.  Every JavaScript framework has their own autocomplete widget and many of them have become quite advanced.  Much like the placeholder attribute's introduction to markup, a frequently used...

Discussion

  1. I might be interested in something like this. I wonder however, about the effects it has on load time and cpu cycles on the server. Do you know if larger sites are using this?

    Mark

  2. David Duymelinck

    I used the code to add a compression option to the CodeIgniter framework but i noticed your regular expressions removed begin tags and content. So i adjusted it;

    $search = array('/>[\n\r ]+/s','/[\t ]+/s');
    $replace = array('>','
    
  3. @Mark: The only “larger” site I know of that crunches their HTML code is a small upstart called “Google” ;). If you view their search result source, you’ll see that most the page is on one line.

    My thought has always been that if you need another server to handle this, get one (of course, only if it’s feasible). User’s shouldn’t have to carry this burden.

    @David: I’ll take a look at what you’ve presented later today.

  4. Fair enough :) I will be testing/adding this to my sites soon.

  5. This is really, REALLY something a lot more sites should be doing. It’s so simple and effective.

  6. This study points out how useless it is to compress HTML on common websites/weblogs.

    I hope it helps.

  7. I also noticed the regular expressions removed begin tags and content.
    I tried @david’s suggestion and and that didn’t work either, this did:

    $search = array("/>[[:space:]]+/", "/[[:space:]]+</");
    $replace = array(">","<");
    

    Shaun

  8. Nouman Saleem

    @ louis – that study was done using html tidy, all that did was remove empty lines – not place it on a single line.

  9. @Nouman: I don’t understand your remark. Your PHP code “gets rid of tabs, line breaks, and extra spaces”, and as I initially pointed out, that is not a relevant thing to do to optimize loading times and co.

  10. Nouman Saleem

    @ loius as I said that was done using html tidy which doesnt do what this script does, unless Im mistaken. This script makes it like the google source code where the files is compressed way further than what html tidy can do

  11. @Nouman: what is “way further” exactly? If it’s just the removal of the newlines, I don’t believe that it will be enough to say that the same conclusion as the study I pointed to doesn’t apply here.

    The removal of human-dedicated characters is not interesting when digging out to optimize performances because (a) there’s too little to win for normal size webpages, and (b) the gzip compression make advantage of the redundance of these special characters and thus compress the page effisciently enough.

  12. Neat! Very effective, perfect for inline documentation.

  13. @Shaun: same problem, you solution worked.

  14. I rewrote the algorithm as My solution was incomplete (remove comments, tabs, spaces, newlines, etc):

    compress_page($buffer) {
    $search = array(
        "/ +/" => " ",
        "/<!--\{(.*?)\}-->|<!--(.*?)-->|[\t\r\n]|<!--|-->|\/\/ <!--|\/\/ -->|<!\[CDATA\[|\/\/ \]\]>|\]\]>|\/\/\]\]>|\/\/<!\[CDATA\[/" => ""
    );
    $buffer = preg_replace(array_keys($search), array_values($search), $buffer);
    return $buffer;
    }
    

    this compresses all html, and javaScript but not CSS for this I use:

    compress_styles($buffer) {
    // remove comments, tabs, spaces, newlines, etc.
    $search = array(
        "/\/\*(.*?)\*\/|[\t\r\n]/s" => "",
        "/ +\{ +|\{ +| +\{/" => "{",
        "/ +\} +|\} +| +\}/" => "}",
        "/ +: +|: +| +:/" => ":",
        "/ +; +|; +| +;/" => ";",
        "/ +, +|, +| +,/" => ","
    );
    $buffer = preg_replace(array_keys($search), array_values($search), $buffer);
    return $buffer;
    }
    

    Hope this is useful to someone.

  15. Really cool feature

  16. Uzo

    Oh this piece of code has been godsend to me. Extremely easy to set up and very noticable rewards even on an empty cache. Thanks!

  17. [code]
    ob_start();
    // INIT AND START THE APPLICATION
    include_once(“includes” . DS . “init.inc.php”);
    $sContent = ob_get_contents();
    ob_clean();

    $content = str_replace(array(“\n”, “\r”, “\t”, “\o”, “\xOB”), ”, $sContent);
    [/code]

  18. compress_styles($buffer) {
    // remove comments, tabs, spaces, newlines, etc.
    $search = array(
    "/\/\*(.*?)\*\/|[\t\r\n]/s” => “”,
    “/ +\{ +|\{ +| +\{/” => “{“,
    “/ +\} +|\} +| +\}/” => “}”,
    “/ +: +|: +| +:/” => “:”,
    “/ +; +|; +| +;/” => “;”,
    “/ +, +|, +| +,/” => “,”
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!