All TalkersCode Topics

Follow TalkersCode On Social Media

Compress HTML Code Using PHP

Last Updated : Jul 1, 2023


In this tutorial we will show you how to compress your HTML code using PHP, compressing the code is very beneficial for a website it increases website performance and load it faster by making webpage smaller and lighter and it also affects website SEO.

You may also like convert HTML to PDF using PHP.

Compress HTML Code Using PHP

To Compress HTML Code It Takes Only One Step:-

  1. Make a PHP file to compress code

Step 1. Make a PHP file to compress code

We make a PHP file and save it with a name compress.php


function compress_code($code) 
 $search = array(
  '/\>[^\S ]+/s',  // remove whitespaces after tags
  '/[^\S ]+\</s',  // remove whitespaces before tags
  '/(\s)+/s'       // remove multiple whitespace sequences

 $replace = array('>','<','\\1');
 $code = preg_replace($search, $replace, $code);
 return $code;

<p>Compress HTML Code Using PHP</p>


In this step we use ob_start() and then call compress_code() function and under this function we create two array to replace and remove whitespaces and then return the code.

Our HTML Code lies between ob_strart() and ob_flush() after creating this run the script and view webpage source you will notice compressing of your HTML code. You may also like read HTML from text file using PHP.

Thats all, this is how to compress HTML code using PHP. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

I hope this tutorial on minify HTML php helps you and the steps and method mentioned above are easy to follow and implement.

Latest Tutorials