Remove whitespace from HTML
It's been a while since this question was first asked but I still see the need to post this answer in order to help people with the same problem.
None of these solutions were adoptabe for me therefore I've came up with this solution: Using output_buffer
.
The function ob_start
accepts a callback as an argument which is applied to the whole string before outputting it. Therefore if you remove whitespace from the string before flushing the output, there you're done.
/**
* Remove multiple spaces from the buffer.
*
* @var string $buffer
* @return string
*/
function removeWhitespace($buffer)
{
return preg_replace('/\s+/', ' ', $buffer);
}
ob_start('removeWhitespace');
<!DOCTYPE html>
<html>
<head></head>
<body></body>
</html>
ob_get_flush();
The above would print something like:
<!DOCTYPE html> <html> <head> </head> <body> </body> </html>
Hope that helps.
HOW TO USE IT IN OOP
If you're using object-orientated code in PHP you may want to use a call-back function that is inside an object.
If you have a class called, for instance HTML, you have to use this code line
ob_start(["HTML","removeWhitespace"]);
$html = preg_replace('~>\s+<~', '><', $html);
But I don't see the point of this. If you're trying to make the data size smaller, there are better options.