Skip to content

Instantly share code, notes, and snippets.

@aarongustafson
Created March 9, 2011 16:01
Show Gist options
  • Save aarongustafson/862452 to your computer and use it in GitHub Desktop.
Save aarongustafson/862452 to your computer and use it in GitHub Desktop.
PHP-based compression of HTML & CSS (doesn't compress whitespace in <pre> elements)
# compress the code
php_value auto_prepend_file ./prepend.php
php_value auto_append_file ./append.php
<?php
/* -----------------------------------------------------------------------------
* Function: tidy_up( $buffer )
* Purpose: Clean up the markup
* ---------------------------------------------------------------------------*/
function tidy_up( $buffer )
{
# remove extra paragraphs
$buffer = preg_replace( '/<p><\/p>/', '', $buffer );
return $buffer;
}
/* -----------------------------------------------------------------------------
* Function: mobilize( $buffer )
* Purpose: Compresses HTML for mobile delivery
* ---------------------------------------------------------------------------*/
function mobilize( $buffer )
{
$chunks = preg_split( '/(<pre.*?\/pre>)/ms', $buffer, -1, PREG_SPLIT_DELIM_CAPTURE );
$buffer = '';
foreach ( $chunks as $c )
{
if ( strpos( $c, '<pre' ) !== 0 )
{
# remove new lines & tabs
$c = preg_replace( '/[\\n\\r\\t]+/', ' ', $c );
# remove extra whitespace
$c = preg_replace( '/\\s{2,}/', ' ', $c );
# remove inter-tag whitespace
$c = preg_replace( '/>\\s</', '><', $c );
# remove CSS & JS comments
$c = preg_replace( '/\\/\\*.*?\\*\\//i', '', $c );
}
$buffer .= $c;
}
return $buffer;
}
$buffer = ob_get_clean();
# don't compress JS files this way (some aren't ready for it)
if ( preg_match( "/\.js/", $_SERVER['REQUEST_URI'] ) === 0 )
{
echo mobilize( tidy_up( $buffer ) );
}
else
{
# you could use YUI compressor here
echo $buffer;
}
?>
<?php ob_start(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment