April 28, 2007

Reducing HTML output size

I recently found myself writing a small web app for my friend Brian to use on his cell phone, one of the last places where page size really matters. Since every character counts, we want to keep our page structure lean and mean (probably a good idea on a mobile device anyway). But after that there’s a lazy, completely pain-free step we can take: stripping all of the redundant whitespace from our HTML.

With PHP’s output buffer handlers we can just set it and forget it:

function clean_html($output){
	$output = preg_replace("/\n/", "", $output);
	$output = preg_replace("/\t/", "", $output);
	$output = preg_replace("/\s+/", " ", $output);
	return $output;
}
 
ob_start('clean_html');
 
//a bunch of stuff that prints out html
 
ob_flush();

This will give use one long, ugly line of dense markup, but what do we care? It’s still valid and the browser handles it just fine. This seems to reduce page size by about 10-20% in this particular application.

7 Responses

  1. 1 jason parchment

    i’d like to use this some day. perhaps when i start caring about other people’s cell billz. lolz u no??

  2. 2 joey

    jase you should be worried about your mom’s cell bill, she’s callin me like 24/7

  3. 3 jason parchment

    she has free national calling it’s all good. also, a raging yeast infection.

  4. 4 joey

    oh she might want to get a hepatitis test too, keep it on the dl.

  5. 5 so guay

    GAY

  6. 6 alfonso ribiero

    WHAT

  7. 7 VIOLETTA WALLACE

    DEY TOOK MY SON. OVER WHAT? SOME MUSIC? IT HURTS, IN MI CHEST.

Leave a Reply