How to minify php page html output?

To minify HTML output in PHP, you can use the following steps:

  1. Use the trim() function to remove extra whitespace from the beginning and end of the HTML code.
  2. Remove extra whitespace between HTML tags using preg_replace() function with a regular expression.
  3. Remove extra lines using preg_replace() function with a regular expression.

Watch a course Learn object oriented PHP

Here's some sample code that demonstrates how to do this:

<?php

$html = '
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>';

// Remove extra whitespace from beginning and end of HTML code
$html = trim($html);

// Remove extra whitespace between HTML tags
$html = preg_replace('/\s+/', ' ', $html);

// Remove extra lines
$html = preg_replace('/\n+/', '', $html);

// Remove spaces between opening and closing HTML tags
$html = preg_replace('/>\\s+</', '><', $html);

echo $html;

This will output the following minified HTML:

<html><head><title>My Page</title></head><body><h1>Hello, World!</h1></body></html>