Check Out The Latest Themes And Exclusive Deals And Offers On Themes
In Our Deals For Web Developers Section


Join Today And Get All The 87 Themes In Just $69! Join Today

Compress HTML Code Using PHP

Tuesday, Mar 7, 2017

Tags:- HTML 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. 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

<?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.

Join Us With Our 21000+ Subscribers And Get Our Latest Tutorials Update Via Email