Reputation: 107
Very quick question about programming practices here:
I've always used echo() to output HTML code to the user as soon as it was generated, and used ob_start() at the same time to be able to output headers later in the code. Recently, I was made aware that this is bad programming practice and I should be saving HTML output until the end.
Is there a reason for this? What is it, and why isn't output buffering a good alternative?
Thanks!
Upvotes: 2
Views: 265
Reputation: 490607
It is good to handle all sorts of things before you output in a view - for example, you may need to send additional headers such as Location
and Set-Cookie
.
Also, you never know what kind of view you will need - this response this time is HTML, but what if you want it as JSON or XML later? You'll have a difficult time restructuring.
If you had left all output to a final view, you could swap the HTML for an XML template.
Upvotes: 1
Reputation: 522597
Some thoughts, not necessarily in order.
Using echo
to output HTML is messy. PHP is a template language, you can break out of it if you need to output HTML:
<?php echo "<div id=\"foo\">" . $bar . "</div>"; ?>
vs
<div id="foo"><?php echo $bar; ?></div>
Look into the MVC pattern.
Upvotes: 2
Reputation: 57318
Whenever any HTML is sent to the browser, headers are received/created. PHP can't send any more headers after this happens. So, by sending code "early", you're disabling PHP's ability to send headers, and limiting the flexibility of your code (either now or for future changes).
Upvotes: 1