0

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.)

1 Answer 1

2

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);
?>
Sign up to request clarification or add additional context in comments.

2 Comments

If I understand correctly, this seems great. But could you explain a bit more: what is ob_start() and ob_get_clean() in relationship to preg_replace()?
ob_start starts buffering, ob_get_clean stops buffering and returns what has been buffered. preg_replace is then used to remove white spaces from what has been buffered, and echo the result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.