Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minify HTML, but don't touch PHP with Gulp

The problem

I have a lot of .php files, mostly containing HTML, but also some PHP lines on top (e.g. form trigger code or similar). So they look like

<?php
if($someValue){
    //doSth
}
//more content
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <title>My Website</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
<!-- Content and scripts here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</body>
</html>

The goal

My goal is to minify the HTML (and maybe even the inline javascript, but that's just a little extra), without touching the PHP on top. I'm using Gulp as automated build tool and would like to see a solution using this tool and any extra packages as they are needed.

like image 983
manniL Avatar asked Oct 17 '16 15:10

manniL


People also ask

How do I minify PHP HTML output?

Use the ob_start() Function With a Callback to Minify HTML Output of the PHP Page. You can use the ob_start() function with a callback to remove whitespaces before and after the tags, comments, and whitespace sequences.

Can you minify HTML?

To minify JS, CSS and HTML files, comments and extra spaces need to be removed, as well as crunch variable names so as to minimize code and reduce file size. The minified file version provides the same functionality while reducing the bandwidth of network requests.

Can PHP be Minified?

Minification can be done by removing unnecessary details and eliminating excessive whitespaces, newlines, comments, etc. However, minification reduces the readability of the code. Minification can reduce file size upto 70%. PHP is used to transfer files from development to production environment.


1 Answers

The gulp-htmlmin module uses the html-minifier module, which has plenty of options (displayed on both its npmjs.com and github pages) that can be used. The option we will focus on is ignoreCustomFragments.

var gulp = require(gulp),
    htmlmin = require(gulp-htmlmin);

gulp.task('htmltask', function(){
  return gulp.src(['./dev/*.html','./dev/*.php'])
      .pipe(htmlmin({
        collapseWhitespace: true,
        ignoreCustomFragments: [ /<%[\s\S]*?%>/, /<\?[=|php]?[\s\S]*?\?>/ ]
      }))
      .pipe(gulp.dest('./site'));
});

In the above code, you see we are using ignoreCustomFragments with the regex /<\?[=|php]?[\s\S]*?\?>/ to ignore code starting with <? and <?php and ending with ?>.

By default, html-minifier ignores php, so you don't have to worry about setting ignoreCustomFragments.

EDIT Thanks amersk

Some php files you work with may not have closing tags, for example many WordPress files do not. An alternative would be to use the following instead:

ignoreCustomFragments: [/<\?[\s\S]*?(?:\?>|$)/]

like image 101
Howard Davis Avatar answered Sep 19 '22 18:09

Howard Davis