i'm looking for a way to keep my HTML code output via PHP clean.
If you look into the source code, the result looks like this:
<section><div class="card">
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in</p>
<a href="#" class="btn btn-primary">Go somewhere</a> </div>
</div>
</section><section><div class="card">
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a> </div>
</div></section>
I want it to look like this:
<section>
<div class="card">
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in</p>
<a href="#" class="btn btn-primary">Go somewhere</a> </div>
</div>
</section>
<section>
<div class="card">
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in</p>
<a href="#" class="btn btn-primary">Go somewhere</a> </div>
</div>
</section>
this is my php output code:
ob_start();
include_once ROOT.'/global/header.php';
print $content_output; // the included files
include_once ROOT.'/global/footer.php';
$output = ob_get_contents();
ob_end_clean();
echo $output;
The reason for this is that I am building a scaffold where blocks are created for a website. For example the start page consists of block2, block7, block1 and block5. At the end the customer gets a clean HTML, which consists of the above mentioned blocks.
You can use DOMDocument to process & format HTML. DOMDocument is tough to use & much of it could use better documentation.
If all you want to do is pretty print the html, something like this should do what you need:
You could also look for an html beautifier, but it doesn't look like there's any particularly mature projects for that.
I also want to add that running DOMDocument on every single request to format html adds additional overhead. More cpu cycles means more energy, so something to be mindful of. You probably won't see any real change in script execution time though.
Some existing projects that might make DOM work easier for you. Things to maybe try if DOMDocument doesn't do quite what you want (I'm not 100% sure the code above will do the trick, nor do I know if any of these repos can definitely solve your problem):