After the last part in this series on PHP program control structures, I got a number of requests for a post on integrating PHP and HTML. It’s actually quite simple to integrate PHP and HTML; for the most part, a PHP script can be treated as an HTML page, with bits of PHP inserted here and there. Anything in a PHP script that is not contained within <?php ?> tags is ignored by the PHP compiler and passed directly to the web browser as-is.
Let’s take a look at a very simple example of what a full PHP script might look like:
Welcome, today is <?php echo date('l, F jS, Y'); ?>.
You can see that the majority of the code above is simply HTML, with just a bit of PHP that prints out today’s date using the built-in date function. Like I mentioned above, all of the plain HTML in the code above will be ignored by the PHP compiler and passed through to the web browser untouched.
Using HTML Inside of Program Control Structures
We can combine what we learned last time about program control structures to integrate PHP and HTML. Let’s see an example using an if/else block to display a holiday message on your website:
<?php if (date('n/j') == '12/25') : ?>
<?php else : ?>
<p>Welcome to my website.</p>
<?php endif; ?>
The code above would display “Merry Christmas” on December 25th, and “Welcome to my website.” on every other day of the year. You may notice that the if/else structure is a little different that what I showed you last time. This is an alternative form that is a little easier to use when integrating PHP and HTML. Each of your conditional statements are followed by a colon, and you must end the if/else block with an endif (and don’t forget that semicolon!). You can do something similar with for and while loops, ending with endfor and endwhile, respectively. This method can be useful for displaying tabular data:
<?php for ($i=1; $i<=10; $i++) : ?>
<tr><td><?php echo $i; ?></td></tr>
<?php endfor; ?>
See how easy that is? Integrating PHP and HTML is really very simple. Just remember that at its core, a PHP script is just an HTML page with some PHP sprinkled through it. If you really wanted to, you could create a PHP script that only had HTML in it, with no <?php ?> tags, and it would work just fine.
For Next Time
Now that we’ve learned how easy it is to integrate PHP and HTML, the next most requested topic has been database access. Almost every “real” web application requires at least a small database, so learning how to query and use that data with PHP is an important topic to cover.