Minify HTML, JavaScript and CSS using PHP

The following script defines a simple PHP function that can minify HTML, JavaScript and CSS codes into one line. Minifying codes is of huge importance as far as web performance is concerned. The less bytes the faster the experience because less bytes of data is to be transferred over the network.

Follow this video for complete guidance :

PHP Function to minify HTML / JavaScript / CSS :

function minify($content, $path = '') {
  $output = preg_replace(
        array(
          '/ {2,}/',
          '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
        ), 
        array(
          ' ',
          ''
        ), 
        $content
      );
  return $output;
}

 

Now call the function to minify any content (HTML, CSS or JavaScript) :

//minify JavaScript
$url = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js";
echo minify(file_get_contents($url));

//minify HTML
$url = "https://reeteshghimire.com.np/";
echo minify(file_get_contents($url));

//minify CSS
$url = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0-beta1/css/bootstrap.css";
echo minify(file_get_contents($url));

 



Recommended For You

About the Author: Admin