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:

	/*  start the output buffer  */

	/*  xhtml code below  */
<!-- all xhtml content here -->
	/*  end the buffer, echo the page content  */

	/*  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

Incredible Demos

  • By
    Downloadify:  Client-Side File Generation Using JavaScript and Flash

    The following tools is in its very beta stages and works intermittently. Its so damn useful that I had to show it off now though! I recently stumbled upon Downloadify, a client-side file generation tool based on JavaScript and Flash ActionScript code. A...

  • By
    CSS Transforms

    CSS has become more and more powerful over the past few years and CSS transforms are a prime example. CSS transforms allow for sophisticated, powerful transformations of HTML elements.  One or more transformations can be applied to a given element and transforms can even be animated...


  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?


  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(">","<");


  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]
    include_once(“includes” . DS . “”);
    $sContent = ob_get_contents();

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

  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!