Reputation: 13565
I know it's a very small performance tweak but I would like to minify an HTML document that has PHP embedded inside of it.
For example:
<div id="header">
<?php
echo "<ul>\n<li>";
echo $somevar;
echo "</li>\n<ul>\n";
?>
</div>
Would produce an output of:
<div id="header">
<ul>
<li>Foobar</li>
<ul>
</div>
But I would like for the output to be minified. I can manually remove spaces and line endings from the PHP output, so it looks like so:
<div id="header">
<ul><li>Foobar</li><ul></div>
But the surrounding HTML document needs to be minified as well. How can this be done? (Imagining this example in a larger document context.)
Upvotes: 0
Views: 557
Reputation: 99921
You can remove all unnecessary whitespaces with a simple regex:
preg_replace('#>\s+<#s', '><', $html);
(This removes all whitespaces between >
and <
chars.)
Now to do this on your generated html code, you can use output buffering:
<?php
ob_start();
// everything bellow is captured and not echoed
?>
<div id="header">
...
</div>
<?php
// get generated html and stop buffering
$html = ob_get_clean();
echo preg_replace('#>\s+<#s', '><', $html);
?>
Upvotes: 2