Log in

View Full Version : PHP & HTML Structure



jdadwilson
03-20-2013, 07:00 PM
Is there a preferred organizational structure for including PHP code into the HTML. For example I have several PHP things that I need to do before any HTML is needed. So, do I construct the script as follows...

<?php
bunch of stuff
?>
<!DOCTYPE >
<html>

<head>

head stuff
</head
<body>

html and php stuff here
</body>
</html>

Or, is this approach better?


<!DOCTYPE >
<html>

<head>

head stuff
</head
<body>

<?php
bunch of stuff
?>
html and php stuff here
</body>
</html>

I realize that it does not really matter, I would just like to know if there is a preference for a standard one way or the other.

TIA...
jdadwilson

djr33
03-20-2013, 07:28 PM
It depends on the exact code you're writing. But generally--

1. Do your configuration, logic and other preparation in PHP before you output any HTML. (Your first example.)
2. Then go through your HTML layout, and use limited PHP to add in content where it needs to go, such as <?php echo $information; ?> within the right HTML <p> element.

As much as possible, separate your HTML layout from your PHP set up. Sometimes that can be hard if you need to use conditional content, in which can you can either try to use it minimally (for example, store a value to use to check in the IF later, rather than calculating things in the middle of the HTML), or you can look into templating, or even output buffers if you must construct a lot of HTML at the top.

There are certain things that MUST go at the top of your script, such as cookies, so in some cases you will need to do this. In other cases, it's just a good habit to get into.

As a simple rule: if you can put it at the top of your script, do that. If not, see how little you can keep in the HTML and move the rest to the top.

Edit: I was hoping traq would add what he'd written (I just couldn't remember the link). I'd suggest starting there:

traq
03-20-2013, 07:58 PM
absolutely. I wrote a bit (http://www.dynamicdrive.com/forums/entry.php?267-Every-PHP-Tutorial-Is-Wrong) about this subject, if you're interested.

jdadwilson
03-21-2013, 03:31 AM
Thanks guys for a great response. Glad to know that I'm on the right track.