Quick question on PHP and HTML rules. Is the code below valid? I want to use php in the head section and body or a website i'm building but i dont want to add extra work for myself.

<html> 
 <title>HTML with PHP</title>
 <body>
 <h1>My Example</h1>

 <?php
include config.php
 $here=$_GET['city'];
 ?>

 <b>Here is some more HTML</b>

 <?php
echo $here;
 ?>

 </body>
 </html>
Member Avatar for diafol

Seems OK to me. Personally, I favour placing any php processing code if mixed with a normal html page, to be placed above the doctype declaration. The only thing to place within the html will then be simple echoes or conditionals (e.g. if/else).

Whats the reasoning behind putting the processing code above the doctype? i've seen that also in tutorials but never knew why.

Member Avatar for diafol

You just keep it all separate. Mixing html and php is a complete mess - especially if you use calls to functions and need to do database query loops etc. Messy.

Also, sometimes you'll use header() or session_start(). If you include these after the DTD, they'll throw an error.

As redirects and header page types frequently occur at the end of conditional routines, they would be bound to fail if there was any html output placed above them.

Debugging mixed php/html is also a pain in the neck.

I tend to use a templating engine (RainTPL) as I can't stand the drudgery of having to <?php ....; ?> every time I want to echo a dynamic value in the page.

If you want to keep cleaner markup, you could look at template engines and MVCs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.