Welcome Guest, Not a member yet? Register   Sign In
Compress HTML output
#1

[eluser]Jérôme Jaglale[/eluser]
To remove useless whitespace from generated HTML, define a 'display_override' hook:

Code:
$CI =& get_instance();
$buffer = $CI->output->get_output();

$search = array(
    '/\>[^\S ]+/s',    //strip whitespaces after tags, except space
    '/[^\S ]+\</s',    //strip whitespaces before tags, except space
    '/(\s)+/s'    // shorten multiple whitespace sequences
    );
$replace = array(
    '>',
    '<',
    '\\1'
    );
$buffer = preg_replace($search, $replace, $buffer);

$CI->output->set_output($buffer);
$CI->output->_display();

Compatible with CI caching mechanism (compressed HTML is cached).


Same thing but with HTML Tidy (PHP 5 only):

Code:
$CI =& get_instance();
$buffer = $CI->output->get_output();

$options = array(
    'clean' => true,
    'hide-comments' => true,
    'indent' => true
    );

$buffer = tidy_parse_string($buffer, $options, 'utf8');
tidy_clean_repair($buffer);
// warning: if you generate XML, HTML Tidy will break it (by adding some HTML: doctype, head, body..) if not configured properly

$CI->output->set_output($buffer);
$CI->output->_display();

Reference: http://maestric.com/en/doc/php/codeignit...press_html
#2

[eluser]brianw1975[/eluser]
i use mod_deflate for apache.

easier to use/configure and probably less cpu intensive.

plus it doesn't require tidy...

BUT I applaud this for being a fantastically simple example of how to do a post processing hook.
#3

[eluser]Jérôme Jaglale[/eluser]
mod_deflate sure has its advantages:
- gzip compression: that's real compression Smile
- also compresses static HTML/XML/text, not only CI-generated contents
but
- older browers have trouble with with gzipped contents
- more CPU intensive (gzip compression at each request)

An advantage of the hook is that it's still plain HTML. Also the "compressed" version can be cached by CI so the "compression" is done only once.

With HTMLTidy you can do things like removing comments, making sure the page is XHTML...




Theme © iAndrew 2016 - Forum software by © MyBB