Want To Be A Blogger  →  Start A Blog  →  Increase Traffic  →  Make Money Online  →  Recommended Things

Compress HTML Code Using PHP

Friday, Jan 5, 2018


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. In this tutorial we will show you how to compress your HTML code using PHP.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.

Subscribe Our Newsletter And Get Tutorials And Offers Via Email

About Me

Hello, My Name is Mudit Jain. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of TalkersCode. I started this blog in february 2015 to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers.