PHPackages                             ctw/ctw-middleware-tidy - 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-tidy

ActiveLibrary

ctw/ctw-middleware-tidy
=======================

This PSR-15 middleware formats, fixes and beautifies the HTML in the Response body using HTML Tidy.

4.0.4(5mo ago)192BSD-3-ClauseHTMLPHP ^8.3CI passing

Since Mar 13Pushed 5mo ago1 watchersCompare

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

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

Package "ctw/ctw-middleware-tidy"
=================================

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

[![Latest Stable Version](https://camo.githubusercontent.com/c9557f39e10dd956b771e194dff47a6b45de4959d64060b740a1c163e1eadcbe/68747470733a2f2f706f7365722e707567782e6f72672f6374772f6374772d6d6964646c65776172652d746964792f762f737461626c65)](https://packagist.org/packages/ctw/ctw-middleware-tidy)[![GitHub Actions](https://github.com/jonathanmaron/ctw-middleware-tidy/actions/workflows/tests.yml/badge.svg)](https://github.com/jonathanmaron/ctw-middleware-tidy/actions/workflows/tests.yml)[![Scrutinizer Build](https://camo.githubusercontent.com/a2cc0c3744ff81fe17b423d517b6371b21dca802436f4700cd66d28ac824de99/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d6d6964646c65776172652d746964792f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-middleware-tidy/build-status/master)[![Scrutinizer Quality](https://camo.githubusercontent.com/d8ff116af482fcdbd4d6f2c8e0cb8292f9097b424fd3db9228bbea72c2f967be/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d6d6964646c65776172652d746964792f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-middleware-tidy/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/d6d5ddf8f54cb6fe35b6e392ed2e481e165497a5ea158f817cba185f5d7b77e1/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d6d6964646c65776172652d746964792f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-middleware-tidy/?branch=master)

PSR-15 middleware that cleans, repairs, and formats HTML responses using PHP's Tidy extension for standards-compliant output.

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

[](#introduction)

### Why This Library Exists

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

HTML generated by template engines and dynamic content systems can contain markup errors, inconsistent formatting, and deprecated constructs. PHP's Tidy extension provides a powerful way to clean and repair HTML, ensuring browser compatibility and standards compliance.

This middleware applies Tidy processing to HTML responses with:

- **Error correction**: Fixes malformed HTML, missing tags, and improper nesting
- **HTML5 compliance**: Ensures valid HTML5 doctype and structure
- **Compact output**: Removes unnecessary whitespace while maintaining readability
- **UTF-8 handling**: Proper encoding for international character support
- **Configurable behavior**: Full control over Tidy's extensive options

### Problems This Library Solves

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

1. **Malformed HTML**: Template engines can produce invalid markup that breaks in some browsers
2. **Missing doctypes**: Tidy's HTML5 mode sometimes strips the doctype; this middleware re-adds it
3. **Inconsistent whitespace**: Source indentation creates bloated output
4. **Encoding issues**: Mixed or incorrect character encoding causes display problems
5. **Legacy markup**: Old HTML constructs need modernization for current standards

### Where to Use This Library

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

- **Production applications**: Ensure all HTML output is valid and standards-compliant
- **Legacy code modernization**: Clean up HTML from older template systems
- **CMS and blog platforms**: Fix user-submitted HTML content
- **API responses**: Guarantee well-formed HTML fragments in API output
- **Development debugging**: Catch HTML errors before they reach production

### Design Goals

[](#design-goals)

1. **Standards compliance**: Output valid HTML5 documents
2. **Safe processing**: Returns original HTML if Tidy processing fails
3. **Doctype preservation**: Re-adds HTML5 doctype when needed
4. **Configurable options**: Full access to Tidy's configuration parameters
5. **Statistics tracking**: Appends compression/change statistics as HTML comment

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

[](#requirements)

- PHP 8.3 or higher
- ext-tidy (PHP Tidy extension)
- ctw/ctw-middleware ^4.0

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

[](#installation)

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

```
composer require ctw/ctw-middleware-tidy
```

Ensure the Tidy extension is enabled in your PHP configuration:

```
extension=tidy
```

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

[](#usage-examples)

### Basic Pipeline Registration (Mezzio)

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

```
use Ctw\Middleware\TidyMiddleware\TidyMiddleware;

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

### ConfigProvider Registration

[](#configprovider-registration)

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

### Default Configuration

[](#default-configuration)

The middleware uses sensible defaults optimized for HTML5:

```
[
    'char-encoding'    => 'utf8',
    'doctype'          => 'html5',
    'bare'             => true,
    'break-before-br'  => true,
    'indent'           => false,
    'indent-spaces'    => 0,
    'logical-emphasis' => true,
    'numeric-entities' => true,
    'quiet'            => true,
    'quote-ampersand'  => false,
    'tidy-mark'        => false,
    'uppercase-tags'   => false,
    'vertical-space'   => false,
    'wrap'             => 10000,
    'wrap-attributes'  => false,
    'write-back'       => true,
]
```

### Configuration Options

[](#configuration-options)

OptionDefaultDescription`char-encoding``utf8`Character encoding for input/output`doctype``html5`Document type declaration`bare``true`Strip Microsoft Office markup`indent``false`Indent block elements`indent-spaces``0`Spaces per indent level`wrap``10000`Line wrap column (high value = minimal wrapping)`tidy-mark``false`Don't add Tidy meta generator tag`quiet``true`Suppress non-essential output### Custom Configuration

[](#custom-configuration)

Override defaults via factory configuration:

```
// config/autoload/tidy.global.php
return [
    'tidy_middleware' => [
        'char-encoding' => 'utf8',
        'doctype'       => 'html5',
        'indent'        => true,
        'indent-spaces' => 2,
        'wrap'          => 120,
    ],
];
```

### Output Statistics

[](#output-statistics)

The middleware appends an HTML comment showing processing statistics:

```

```

FieldDescription`in`Original HTML size in bytes`out`Processed HTML size in bytes`diff`Size reduction percentage### HTML5 Doctype Handling

[](#html5-doctype-handling)

Tidy may strip the HTML5 doctype during processing. This middleware automatically re-adds it when the `doctype` option is set to `html5`:

```
>

...

```

### Selective Processing

[](#selective-processing)

The middleware automatically:

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

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance71

Regular maintenance activity

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity79

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 ~52 days

Recently: every ~131 days

Total

34

Last Release

165d ago

Major Versions

1.0.4 → 2.0.02022-02-14

2.0.0 → 3.0.02022-07-07

3.0.21 → 4.0.02024-06-18

PHP version history (4 changes)1.0.0PHP ^7.4 || ^8.0

3.0.0PHP ^8.0

3.0.9PHP ^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 (63 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[pimple/pimple

Pimple, a simple Dependency Injection Container

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

Flow Application Framework

862.0M449](/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)
