1. <?php
  2. /**
  3. * Formats HTML output for non-production use.
  4. *
  5. * This function applies basic formatting to HTML output,
  6. * including indentation and line breaks, to improve readability.
  7. *
  8. * @param string $html The HTML string to format.
  9. * @return string The formatted HTML string.
  10. */
  11. function formatHtml(string $html): string
  12. {
  13. // Use HTMLPurifier to safely format HTML.
  14. // This helps prevent XSS vulnerabilities.
  15. $purifier = new \HTMLPurifier();
  16. $config = $purifier->getDefConfig();
  17. $purifier->config($config);
  18. // Format the HTML content.
  19. $formattedHtml = $purifier->purify($html);
  20. // Indent the HTML for better readability.
  21. $lines = explode("\n", $formattedHtml);
  22. $indentedLines = array_map(function ($line) {
  23. return str_repeat(" ", strlen(str_getcsv($line, "\n", PHP_EOL)) ); // Indent by 4 spaces
  24. }, $lines);
  25. // Join the indented lines back into a single string.
  26. $formattedHtml = implode("\n", $indentedLines);
  27. return $formattedHtml;
  28. }
  29. //Example usage (for testing)
  30. if (isset($_GET['format'])) {
  31. $html = $_GET['html'];
  32. echo formatHtml($html);
  33. }
  34. ?>

Add your comment