How to Minify HTML code?

A bit late but still... By using output_buffering it is as simple as that:

function compress($string)
{
    // Remove html comments
    $string = preg_replace('/<!--.*-->/', '', $string);

    // Merge multiple spaces into one space
    $string = preg_replace('/\s+/', ' ', $string);   

    // Remove space between tags. Skip the following if
    // you want as it will also remove the space 
    // between <span>Hello</span> <span>World</span>.
    return preg_replace('/>\s+</', '><', $string);      
}

ob_start('compress');

// Here goes your html.    

ob_end_flush();

You could parse the HTML code into a DOM tree (which should keep content whitespace in the nodes), then serialise it back into HTML, without any prettifying spaces.


Is there any tools that can do it?

Yes, here's a tool you could include into a build process or work into a web cache layer: https://code.google.com/archive/p/htmlcompressor/

Or, if you're looking for a tool to minify HTML that you paste in, try: http://www.willpeavy.com/minifier/