Last active
November 18, 2023 13:18
-
-
Save atelierbram/c5a31d19277ff7bfc38c078f69f6f3b5 to your computer and use it in GitHub Desktop.
PHP Function to Minify HTML Output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taken from davidwalsh.name/php-output-buffers - updated function: see comment by Shaun.