Just a Thought

To the Point: Minify HTML Using Only Vanilla PHP

Here's a cheap trick you can use to easily, and safely, minify HTML using only vanilla PHP:

$html '<Your HTML goes here>';

// If you're minifying HTML5, this will suppress warnings about HTML5-specific elements (e.g. `section`).
$prevUseLibxmlInternalErrors libxml_use_internal_errors(true);

$domDocument = new DOMDocument();
$domDocument->formatOutput false;
$domDocument->loadHTML($htmlLIBXML_NOBLANKS);

$minifiedHtml $domDocument->saveHTML();

// Restore the previous setting.
libxml_use_internal_errors($prevUseLibxmlInternalErrors);

The output (probably) won't be completely minified but the HTML will be smaller than before. And no need for a third-party library 🎉

It's likely you won't see earth-shattering results using this technique alone, but it's one of many ways we can reduce the weight of our Web pages. For example, you could take this same code one step further by also minifying all embedded CSS in the DOMDocument. The following snippet uses the CSS-minifier in Marigold to do just that. You can do a really good job of minifying CSS without going to extreme lengths, so you mightn't need a third-party library to do this, either.

$html '<Your HTML goes here>';

$prevUseLibxmlInternalErrors libxml_use_internal_errors(true);

$domDocument = new DOMDocument();
$domDocument->formatOutput false;
$domDocument->loadHTML($htmlLIBXML_NOBLANKS);

$cssMinifier = new CssMinifier();

foreach (
$domDocument->getElementsByTagName('style') as $styleElem) {
    if (
null === $styleElem->nodeValue) {
        continue;
    }

    
$styleElem->nodeValue $cssMinifier->minify($styleElem->nodeValue);
}

$minifiedHtml $domDocument->saveHTML();

libxml_use_internal_errors($prevUseLibxmlInternalErrors);

This is how I'm currently minifying the cached error pages in Miniblog.

Now, minifying both HTML and CSS does result in a significant reduction in page weight: on the demo Miniblog homepage, the content-length of the response body was reduced by 38%.