akankov / html-min
HTML compressor and minifier for PHP 8.3+
Fund package maintenance!
Requires
- php: 8.3.* || 8.4.* || 8.5.*
- ext-dom: *
- ext-libxml: *
- ext-mbstring: *
- psr/http-factory: ^1.0
- psr/http-message: ^1.1 || ^2.0
- psr/http-server-middleware: ^1.0
- psr/log: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.65
- infection/infection: ^0.33
- nyholm/psr7: ^1.8
- phan/phan: ^6.0
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.0
- rector/rector: ^2.0
Suggests
- matthiasmullie/minify: Aggressive inline CSS/JS minification. Wire via HtmlMin::setInlineCssMinifier() / setInlineJsMinifier().
- dev-master
- v2.8.0
- v2.7.1
- v2.7.0
- v2.6.1
- v2.6.0
- v2.5.1
- v2.5.0
- v2.4.0
- v2.3.0
- v2.2.0
- v2.1.0
- v2.0.0
- v1.2.0
- v1.1.0
- v1.0.1
- v1.0.0
- v1.0.0-alpha.1
- dev-release/v2.8.0
- dev-refactor/drop-redundant-parser-preprocessing
- dev-test/kill-observable-mutants
- dev-release/v2.7.1
- dev-test/finish-coverage
- dev-test/cover-htmlparser
- dev-test/raise-coverage-and-msi
- dev-release/v2.7.0
- dev-refactor/extract-doctype-builder
- dev-refactor/extract-whitespace-normalizer
- dev-refactor/extract-inline-content-minifier
- dev-refactor/extract-dom-serializer
- dev-refactor/extract-optional-tag-omission
- dev-fix/placeholder-collision-nonce
- dev-refactor/data-driven-attribute-removals
- dev-docs/coverage-mutation-badges
- dev-test/kill-mutants-observer-attrs
- dev-test/kill-escaped-mutants
- dev-ci/coverage-and-mutation-testing
- dev-fix/inline-minifier-edge-cases
This package is auto-updated.
Last update: 2026-05-31 17:22:54 UTC
README
html-min
A fast HTML5 compressor and minifier for PHP. Strips redundant whitespace, comments, optional tags, and default attributes, then sorts what's left so your gzip layer has less work to do.
Built on native \DOMDocument — no third-party DOM dependencies.
Requirements
- PHP 8.3, 8.4, or 8.5
- ext-dom, ext-libxml, ext-mbstring
Installation
composer require akankov/html-min
Usage
use Akankov\HtmlMin\HtmlMin; $html = <<<HTML <html> <body> <ul style=""> <li style="display: inline;" class="foo">One</li> <li class="foo" style="display: inline;">Two</li> </ul> </body> </html> HTML; echo (new HtmlMin())->minify($html); // <html><body><ul><li class=foo style="display: inline;">One<li class=foo style="display: inline;">Two</ul>
Wrap any block in <nocompress>…</nocompress> to keep its whitespace intact.
Configuration
Every option is a chainable setter. All defaults are shown — the example below reproduces the default configuration.
$htmlMin = (new HtmlMin()) // Core ->doOptimizeViaHtmlDomParser(true) // run the DOM-based pass (required for most of the flags below) ->doRemoveComments(true) // drop HTML comments (conditional comments are preserved) ->doSumUpWhitespace(true) // collapse runs of whitespace in text nodes ->doRemoveWhitespaceAroundTags(false)// aggressive: also trim whitespace adjacent to block tags ->doRemoveSpacesBetweenTags(false) // aggressive: remove whitespace-only text nodes between elements // Attribute optimization ->doOptimizeAttributes(true) ->doSortHtmlAttributes(true) // canonical attribute order → better gzip ->doSortCssClassNames(true) // canonical class order → better gzip ->doRemoveOmittedQuotes(true) // class="foo" → class=foo when safe ->doRemoveOmittedHtmlTags(true) // <p>x</p> → <p>x where the closing tag is optional ->doRemoveEmptyAttributes(true) ->doRemoveValueFromEmptyInput(true) ->doRemoveDefaultAttributes(false) // opt-in: drop defaults like form method=get // URL attribute trimming ->doRemoveHttpPrefixFromAttributes(false) ->doRemoveHttpsPrefixFromAttributes(false) ->doKeepHttpAndHttpsPrefixOnExternalAttributes(false) ->doMakeSameDomainsLinksRelative([]) // e.g. ['example.com'] → strip host from same-site links // Deprecated attribute cleanup ->doRemoveDeprecatedAnchorName(true) ->doRemoveDeprecatedScriptCharsetAttribute(true) ->doRemoveDeprecatedTypeFromScriptTag(true) ->doRemoveDeprecatedTypeFromStylesheetLink(true) ->doRemoveDeprecatedTypeFromStyleAndLinkTag(true) ->doRemoveDefaultMediaTypeFromStyleAndLinkTag(true) ->doRemoveDefaultTypeFromButton(false) // Inline CSS / JS minification (opt-in, off by default) ->doMinifyInlineCss(false) // minify the contents of inline <style> blocks ->doMinifyInlineJs(false); // minify the contents of inline <script> blocks echo $htmlMin->minify($html);
Each setter returns $this, so you can configure and call minify() in one chain.
Inline CSS and JS minification
By default the contents of <style> and <script> blocks round-trip untouched.
Enable the two opt-in toggles to minify them:
$htmlMin = (new HtmlMin()) ->doMinifyInlineCss(true) ->doMinifyInlineJs(true); echo $htmlMin->minify($html);
The bundled minifiers are zero-dependency and conservative:
- CSS — strips
/* … */comments and collapses whitespace; the contents of strings andurl(…)are preserved. - JS — removes comments and collapses horizontal whitespace while preserving newlines (so Automatic Semicolon Insertion is unaffected), strings, regex literals, and template literals. Identifiers are never renamed.
Scripts that are not JavaScript are left alone automatically: a <script>
whose type is, for example, application/ld+json or text/x-template, and any
<script src="…">, passes through unminified.
Using a different minifier
For aggressive minification (identifier renaming, dead-code removal), plug in a
third-party tool with setInlineCssMinifier() / setInlineJsMinifier(). Each
takes any callable(string): string; pass null to restore the bundled default.
use MatthiasMullie\Minify; // composer require matthiasmullie/minify $htmlMin = (new HtmlMin()) ->doMinifyInlineCss(true) ->doMinifyInlineJs(true) ->setInlineCssMinifier(static fn (string $css): string => (new Minify\CSS($css))->minify()) ->setInlineJsMinifier(static fn (string $js): string => (new Minify\JS($js))->minify()); echo $htmlMin->minify($html);
If a bundled minifier throws, the original source is kept and a warning is sent
to the PSR-3 logger (when one is set via setLogger()), so a minifier bug can
never corrupt the page. User-supplied callables let their exceptions propagate.
Extending
To run your own pass over every element during minification, implement
Akankov\HtmlMin\Contract\DomObserver and register it:
use Akankov\HtmlMin\Contract\DomObserver; use Akankov\HtmlMin\Contract\HtmlMinInterface; use Akankov\HtmlMin\HtmlMin; final class StripDataTestIds implements DomObserver { public function domElementBeforeMinification(\DOMElement $element, HtmlMinInterface $htmlMin): void { } public function domElementAfterMinification(\DOMElement $element, HtmlMinInterface $htmlMin): void { if ($element->hasAttribute('data-testid')) { $element->removeAttribute('data-testid'); } } } $htmlMin = new HtmlMin(); $htmlMin->attachObserverToTheDomLoop(new StripDataTestIds()); echo $htmlMin->minify($html);
Benchmarks
Measured against voku/html-min, wyrihaximus/html-compress, zaininnari/html-minifier, and abordage/html-min on a corpus of real-world HTML pages.
| adapter | median ms/op | geomean ms/op | parse failures | avg gzipped ratio |
|---|---|---|---|---|
| akankov/html-min | 1.9 | 1.9 | 0 / 15 | 90.7% |
| akankov/html-min (inline) | 2.1 | 2.5 | 0 / 15 | 87.6% |
| voku/html-min | 3.3 | 3.6 | 0 / 15 | 90.7% |
| wyrihaximus/html-compress | 6.0 | 7.5 | 0 / 15 | 87.0% |
| zaininnari/html-minifier | 9.5 | 8.3 | 0 / 15 | 94.8% |
| abordage/html-min † | 0.2 | 0.2 | 0 / 15 | 90.2% |
The table above is regenerated by make bench from the latest run.
See latest.md for the per-fixture detail (speed, peak memory,
gzipped compression ratio, methodology, and non-claims). Reproduce with
make bench-install && make bench (requires Docker).
Development
composer install make md-check # markdown formatting (Docker) vendor/bin/phpunit # tests vendor/bin/phpstan analyse # static analysis (level max) vendor/bin/php-cs-fixer fix # code style
CI runs the full matrix (PHP 8.3 / 8.4 / 8.5) on every push and pull request.
License
MIT — see LICENSE.
Originally authored by Lars Moelleken; maintained in this fork by Alex Kankov.