2

I have a function that compress the php output but it gives me problems with the inline javascript.

I found a page with related topic but the sample from there it's not work: http://jeromejaglale.com/doc/php/codeigniter_compress_html

The problem occur when use // shorten multiple whitespace sequences

If I remove this part from the array the Javascript is working well.

Question:

It's there a possibility to achieve the desired result without the need to use other libraries like Minify or Tidy?

The function:

/**
* [sanitize_output Compress the php output]
* @param  [type] $buffer [ Buffer = ob_get_contents(); ]
* @return [type]         [ string ]
*/
function sanitize_output($buffer)
{

$search = array(
'/\>[^\S ]+/s',         //strip whitespaces after tags, except space
'/[^\S ]+\</s',         //strip whitespaces before tags, except space
'/(\s)+/s',             // shorten multiple whitespace sequences
'/<!--(.|\s)*?-->/',    //strip HTML comments
'#(?://)?<!\[CDATA\[(.*?)(?://)?\]\]>#s', //leave CDATA alone

);
$replace = array(
'>',
'<',
'\\1',
'',
"//<![CDATA[\n".'\1'."\n//]]>",

);

$buffer = preg_replace($search, $replace, $buffer);


return $buffer;

} // End sanitize_output()

The way I use it:

<?php
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();

// ... Code ... Several CSS ... JS ..

$output = ob_get_contents();
ob_end_clean();
$output =  sanitize_output($output);
echo $output;
vascowhite
  • 18,120
  • 9
  • 61
  • 77
Catalin Cardei
  • 304
  • 4
  • 15
  • 2
    Why not use a real optimizer? and enable compression on the connection - it will be more efficient than just stripping whitespace/etc. Also, see [this answer](http://stackoverflow.com/a/1732454/156755) I know it doesn't directly relate but it shows that (x)html and js are very complex to parse and understand correctly with simple string manipulation – Basic Aug 10 '13 at 14:36
  • In this particular case is for a small app that will be deployed on shared servers and the enviroment has a lot of restrictions. What you mean real optimizer ? Can you recommend me some optimizers, or guide me where to get started, what should I use? Thanks! – Catalin Cardei Aug 10 '13 at 19:25
  • 1
    The first that springs to mind is [Google Minify](https://code.google.com/p/minify/). Having compression (and a good cache like [varnish](http://varnish-cache.org)) largely negates the need to minify the html itself. You might get more benefit from minifying the JS (See the [YUI Compressor](http://yui.github.io/yuicompressor/)). Being on shared hosting with little control of the server does limit your options but... It's very rare that a site hosted in shared hosting is busy enough for this kind of micro-optimisation to be useful. I admit that's a generalisation and may not fit your situation. – Basic Aug 10 '13 at 19:49

0 Answers0