<?php
/**
* Formats HTML output for non-production use.
*
* This function applies basic formatting to HTML output,
* including indentation and line breaks, to improve readability.
*
* @param string $html The HTML string to format.
* @return string The formatted HTML string.
*/
function formatHtml(string $html): string
{
// Use HTMLPurifier to safely format HTML.
// This helps prevent XSS vulnerabilities.
$purifier = new \HTMLPurifier();
$config = $purifier->getDefConfig();
$purifier->config($config);
// Format the HTML content.
$formattedHtml = $purifier->purify($html);
// Indent the HTML for better readability.
$lines = explode("\n", $formattedHtml);
$indentedLines = array_map(function ($line) {
return str_repeat(" ", strlen(str_getcsv($line, "\n", PHP_EOL)) ); // Indent by 4 spaces
}, $lines);
// Join the indented lines back into a single string.
$formattedHtml = implode("\n", $indentedLines);
return $formattedHtml;
}
//Example usage (for testing)
if (isset($_GET['format'])) {
$html = $_GET['html'];
echo formatHtml($html);
}
?>
Add your comment