Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP HTML Tidier Middleware

Below is a PSR-15 compatible middleware that will tidy your HTML response after it was generated. This may prove useful in the future, but did not warrant the development of a package (yet).

Steps

<?php

use \Psr\Http\Message\ServerRequestInterface;
use \Psr\Http\Server\MiddlewareInterface;
use \Psr\Http\Server\RequestHandlerInterface;
use \Psr\Http\Message\ResponseInterface;


class MiddlewareTidyHtml implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);
        $tidy = new tidy();

        $config = array(
            'indent'         => true,
            'output-xhtml'   => true,
            'wrap'           => 200
        );

        $tidy->parseString($response->getBody(), $config, 'utf8');
        $tidy->cleanRepair();

        $myStream = fopen('php://temp', 'rw');
        fwrite($myStream, $tidy);
        $newResponse = $response->withBody(new \Slim\Psr7\Stream($myStream));
        return $newResponse;
    }
}

You will need to have installed the tidy extension, which on Ubuntu 24.04 would be a case of running sudo apt-get install php8.3-tidy. Also, this implementation assumes you have the slim/psr7 package, but any alternative PSR-7 stream interface package could be used and swapped out for.

Please refer to the middleware section in my Slim4 cheatsheet if you are using Slim4 and wish to know how to add this to all routes, or only specific ones. Be careful not to apply this to routes that one would expect a response that was not HTML, such as a JSON response for an API or file download.

Last updated: 7th June 2024
First published: 7th June 2024

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch