Skip to content

Instantly share code, notes, and snippets.

@atelierbram
Last active November 18, 2023 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atelierbram/c5a31d19277ff7bfc38c078f69f6f3b5 to your computer and use it in GitHub Desktop.
Save atelierbram/c5a31d19277ff7bfc38c078f69f6f3b5 to your computer and use it in GitHub Desktop.
PHP Function to Minify HTML Output
<?php
// start the output buffer
ob_start('compress_page');
?>
<!-- all html content here -->
<?php
// end the buffer, echo the page content
ob_end_flush();
// function that gets rid of tabs, line breaks, and extra spaces
function compress_page($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;
}
@atelierbram
Copy link
Author

Taken from davidwalsh.name/php-output-buffers - updated function: see comment by Shaun.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment