Beautify WordPress HTML output without any plugins

Great question, I asked it myself and here’s what I came up with. You can just use this in a custom plugin or in functions.php.

// turn on Output Buffering (hence *ob*)
ob_start();
// register a callback to run after WordPress has outputed everything
add_action('shutdown', function () { 
    // get the output buffer and store it to a variable
    $html = ob_get_clean();
    // setup the PHP native html beautifier called tidy
    // note that you need to have libtidy installed
    // but chances are that your server already have it
    $tidy = new \tidy;
    $tidy->parseString($html, [
        'indent' => true,
        'output-xhtml' => true,
        'wrap' => 200
    ], 'utf8');
    $tidy->cleanRepair();
    // output the beautified html
    echo $tidy;
    // Use 0 as third parameter to the add_action so you will
    // register the action as early as possible. Otherwise 
    //  WordPress will flush the output buffer before you do...
}, 0);