Minify HTML Output Using PHP

<?php /** * Minify HTML Output Using PHP * @description To implement add `ob_start("minify_output")` to your main header.php file of your WordPress theme. * @author RakeshS * @link http://stackoverflow.com/questions/6225351/how-to-minify-php-page-html-output * @param $buffer * @return mixed */ function minify_output($buffer) { $search = array( '/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s' ); $replace = array( '>', '<', '\\1' ); if (preg_match("/\<html/i",$buffer) == 1 && preg_match("/\<\/html\>/i",$buffer) == 1) { $buffer = preg_replace($search, $replace, $buffer); } return $buffer; }
This snippet is a quick and easy way to compress and minify your HTML output. To implement add `ob_start("minify_output")` to your main header.php file of your WordPress theme.

2 Responses

Thanks for it, it was very useful.
Thanks for it, it was very useful.

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.