Drupal 7 - Minify HTML output

This solution is now outdated. Prefer using https://www.drupal.org/project/minify.

For reference only, the deprecated solution:

To minify HTML output in Drupal 7, you can remove line breaks. This can be done in your template file html.tpl.php.
Replace

<?php
 
print $page;
?>

By

<?php
    $output
= str_replace(array("\r\n", "\r"), "\n", $page);
   
$lines = explode("\n", $output);
   
$new_lines = array();

    foreach (
$lines as $i => $line) {
      if(!empty(
$line))
         
$new_lines[] = trim($line);
    }
?>
<?php
 
print implode($new_lines);
?>

How does it works

In plain text '\n' is a new line and '\r' is a carriage return. We want to remove them all. The php function str_replace() is good for that.

<?php
 $output
= str_replace(array("\r\n", "\r"), "\n", $page);
?>

We create a new variable that contains the page content where all new lines a replaced by a single new line.

<?php
 $lines
= explode("\n", $output);
?>

The explode() function create an array. We use the \n as separator. At this step, we basically have an array containing 1 paragraph per row.

<?php
 
foreach ($lines as $i => $line) {
  if(!empty(
$line)) $new_lines[] = trim($line);
}
?>

We trim each paragraph. trim() will remove following elements at the beginning and the end of each paragraph.

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab
<?php
 
print implode($new_lines);
?>

Using implode without separator, we finally print the final result.

You may want to strip multiple space as well. To do so replace

<?php
 
print implode($new_lines);
?>

with

<?php
 
print preg_replace('/\s+/', ' ', implode($new_lines));
?>