All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Compress HTML Code Using PHP

Last Updated : Jul 1, 2023

IN - HTML PHP | Written & Updated By - Pragati

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

<?php
ob_start("compress_code");

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;
}

?>
<html>
<body>
<p>Compress HTML Code Using PHP</p>
</body>
</html>

<?php
ob_end_flush();
?>

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.

Author Image About Pragati

Experienced coding content writer who enjoys breaking down complex concepts in programming languages like Java, Python, C, and C++. Over three years of experience producing interesting and relevant content for a variety of entities. Committed to providing concise and easy-to-understand articles that assist readers in easily understanding technology and industry trends in the world of coding and software development.

Follow Pragati On Linkedin 🡪