PHPackages                             ctw/ctw-middleware-htmlminifier - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. ctw/ctw-middleware-htmlminifier

ActiveLibrary

ctw/ctw-middleware-htmlminifier
===============================

This PSR-15 middleware formats, fixes and beautifies the HTML in the Response body using a variety of adapters.

4.0.4(5mo ago)1151BSD-3-ClausePHPPHP ^8.3CI passing

Since Mar 6Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/jonathanmaron/ctw-middleware-htmlminifier)[ Packagist](https://packagist.org/packages/ctw/ctw-middleware-htmlminifier)[ RSS](/packages/ctw-ctw-middleware-htmlminifier/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (5)Versions (23)Used By (0)

Package "ctw/ctw-middleware-htmlminifier"
=========================================

[](#package-ctwctw-middleware-htmlminifier)

[![Latest Stable Version](https://camo.githubusercontent.com/34c8d7f6ef696fa484540b99e7c468654d456eacf00d2c6f65379f578efec9ca/68747470733a2f2f706f7365722e707567782e6f72672f6374772f6374772d6d6964646c65776172652d68746d6c6d696e69666965722f762f737461626c65)](https://packagist.org/packages/ctw/ctw-middleware-htmlminifier)[![GitHub Actions](https://github.com/jonathanmaron/ctw-middleware-htmlminifier/actions/workflows/tests.yml/badge.svg)](https://github.com/jonathanmaron/ctw-middleware-htmlminifier/actions/workflows/tests.yml)[![Scrutinizer Build](https://camo.githubusercontent.com/17204c077eb7f3eb7cb1e84c5eae5b75c82378a792fa8e84d4482119f3b258c0/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d6d6964646c65776172652d68746d6c6d696e69666965722f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-middleware-htmlminifier/build-status/master)[![Scrutinizer Quality](https://camo.githubusercontent.com/7c897d1e7a5a9653bd5079734edd82657849003b490032979b8109a8e2c378d2/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d6d6964646c65776172652d68746d6c6d696e69666965722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-middleware-htmlminifier/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/14e6eae683fade0f6b08ab260f71513a85d5657668c497e224c2dd6f37715149/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d6d6964646c65776172652d68746d6c6d696e69666965722f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-middleware-htmlminifier/?branch=master)

PSR-15 middleware that minifies HTML responses using pluggable adapters, reducing bandwidth and improving page load times.

Introduction
------------

[](#introduction)

### Why This Library Exists

[](#why-this-library-exists)

HTML generated by template engines often contains excessive whitespace, comments, and formatting that increases page size without benefiting end users. Minifying HTML at the response level provides several advantages:

- **Reduced bandwidth**: Smaller responses transfer faster, especially on mobile networks
- **Lower hosting costs**: Less data transferred means reduced bandwidth bills
- **Improved performance**: Smaller payloads parse faster in browsers
- **Production optimization**: Keep source templates readable while serving optimized output

This middleware intercepts HTML responses and minifies them transparently, with multiple adapter options to balance speed versus compression ratio.

### Problems This Library Solves

[](#problems-this-library-solves)

1. **Bloated HTML**: Template engines produce readable but unnecessarily large output
2. **Manual optimization**: Without automation, developers must manually minify HTML
3. **Inconsistent minification**: Different approaches across a codebase lead to varying output quality
4. **Build complexity**: Template-level minification complicates the build process
5. **Debugging difficulty**: Aggressive minification can break HTML; adapters provide different safety levels

### Where to Use This Library

[](#where-to-use-this-library)

- **Production environments**: Reduce HTML size for faster page loads
- **High-traffic sites**: Minimize bandwidth costs at scale
- **Mobile-first applications**: Optimize for slower network connections
- **Content-heavy pages**: Blog posts, documentation, and marketing pages benefit most
- **API responses**: HTML fragments returned by AJAX endpoints

### Design Goals

[](#design-goals)

1. **Pluggable adapters**: Choose the right minification strategy for your needs
2. **Safe defaults**: Conservative minification that won't break valid HTML
3. **Transparent operation**: Works automatically on HTML responses only
4. **Statistics tracking**: Appends an HTML comment showing compression ratio
5. **Zero template changes**: Minifies at response level, not template level

Requirements
------------

[](#requirements)

- PHP 8.3 or higher
- ext-tidy
- ctw/ctw-middleware ^4.0

Installation
------------

[](#installation)

Install by adding the package as a [Composer](https://getcomposer.org) requirement:

```
composer require ctw/ctw-middleware-htmlminifier
```

Usage Examples
--------------

[](#usage-examples)

### Basic Pipeline Registration (Mezzio)

[](#basic-pipeline-registration-mezzio)

```
use Ctw\Middleware\HtmlMinifierMiddleware\HtmlMinifierMiddleware;

// In config/pipeline.php or similar
$app->pipe(HtmlMinifierMiddleware::class);
```

### ConfigProvider Registration

[](#configprovider-registration)

```
// config/config.php
return [
    // ...
    \Ctw\Middleware\HtmlMinifierMiddleware\ConfigProvider::class,
];
```

### Available Adapters

[](#available-adapters)

AdapterDescriptionSpeedCompression`SimpleAdapter`Regex-based whitespace removalFastModerate`TidyAdapter`Uses PHP's Tidy extension for safe minificationMediumGood`WyriHaximusAdapter`Full-featured HTML compressor (requires additional package)SlowerBest### Using SimpleAdapter

[](#using-simpleadapter)

The `SimpleAdapter` uses regular expressions for fast, lightweight minification:

```
use Ctw\Middleware\HtmlMinifierMiddleware\Adapter\SimpleAdapter\SimpleAdapter;
```

Performs:

- Removes multi-line whitespace
- Removes HTML comments
- Collapses multiple spaces
- Strips whitespace around tags

### Using TidyAdapter

[](#using-tidyadapter)

The `TidyAdapter` leverages PHP's Tidy extension for standards-compliant minification:

```
use Ctw\Middleware\HtmlMinifierMiddleware\Adapter\TidyAdapter\TidyAdapter;
```

Features:

- Fixes malformed HTML
- Validates HTML5 doctype
- Configurable output formatting
- Safe for production use

### Using WyriHaximusAdapter

[](#using-wyrihaximusadapter)

For maximum compression, install the optional dependency:

```
composer require wyrihaximus/html-compress
```

```
use Ctw\Middleware\HtmlMinifierMiddleware\Adapter\WyriHaximusAdapter\WyriHaximusAdapter;
```

### Output Statistics

[](#output-statistics)

The middleware appends an HTML comment showing compression statistics:

```

```

FieldDescription`in`Original HTML size in bytes`out`Minified HTML size in bytes`diff`Percentage reduction achieved### Selective Processing

[](#selective-processing)

The middleware automatically:

- Only processes responses with `Content-Type: text/html` or `application/xhtml`
- Passes through empty responses unchanged
- Skips non-HTML responses (JSON, images, etc.)

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance71

Regular maintenance activity

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity70

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~47 days

Recently: every ~131 days

Total

22

Last Release

166d ago

Major Versions

1.0.0 → 3.0.12023-03-07

3.0.14 → 4.0.02024-06-18

PHP version history (3 changes)3.0.0PHP ^8.0

3.0.7PHP ^8.1

4.0.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/18d8bc9bdee8ab1b0cfccce6a06d2438acbed3a58b0046c4834c5678f6769342?d=identicon)[jonathanmaron](/maintainers/jonathanmaron)

---

Top Contributors

[![jonathanmaron](https://avatars.githubusercontent.com/u/298462?v=4)](https://github.com/jonathanmaron "jonathanmaron (28 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ctw-ctw-middleware-htmlminifier/health.svg)

```
[![Health](https://phpackages.com/badges/ctw-ctw-middleware-htmlminifier/health.svg)](https://phpackages.com/packages/ctw-ctw-middleware-htmlminifier)
```

###  Alternatives

[pimple/pimple

Pimple, a simple Dependency Injection Container

2.7k130.5M1.4k](/packages/pimple-pimple)[neos/flow

Flow Application Framework

862.0M450](/packages/neos-flow)[api-platform/state

API Platform state interfaces

223.4M57](/packages/api-platform-state)[internal/dload

Downloads binaries.

98142.7k10](/packages/internal-dload)[symfony/json-streamer

Provides powerful methods to read/write data structures from/into JSON streams.

14440.0k8](/packages/symfony-json-streamer)[rubix/server

Deploy your Rubix ML models to production with scalable stand-alone inference servers.

632.3k](/packages/rubix-server)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
