Home » Internet » Web Designing » How to mix HTML and PHP

How to mix HTML and PHP

When you are working in PHP you often have to write HTML code too. It’s not like once you start working in PHP you cannot write HTML and vice-versa, in fact both are very easily inter-changeable. The only thing you have to take care of is that when you are creating pages, even if there is not a single line of PHP code in 80% of the pages, you should create them as php pages and not as htm or html pages.

If you are primarily working in HTML and occasionally you need to generate some dynamic result you can quickly insert PHP code within <?php and ?>; in fact some prefer just <? and ?> but it’s safer to use the former.

Let’s see an example. Suppose on your about-us.php page you want to tell for how many years you have been into business X. If you started working in 2002 and you write your page in 2010 you might be tempted to write “We have been providing X services for 8 years now.” But what if someone checks your page in 2011 or 2012 and you forget to update your page. They will still see the same number, that is , 8 years. With a little bit of PHP code, the year will increase automatically. Here’s how to do it:

<p>We have been providing X services for <?php echo (date(“Y”)-2002); ?> years now.</p>

This small PHP code makes sure that when someone checks your page in 2011 he or she see the number of years as 9 and not 8.

You can also see an example with some complex code:

        <p>We are going to add two numbers.</p>
        <p>The sum of <?php echo $num1; ?> and <?php echo $num2; ?> is <?php echo $num1 $num2;?></p>

Of course the code could have been more concise but this is to illustrate the example.

Now what if you are extensively working in PHP and you need some HTML output. You simply print the HTML source using either echo or print:

echo “<p>We have been providing X services for ” . (date(“Y”)-2002) . ” years now.</p>”;

So you can see you can easily mix PHP and HTML to create some nicely interactive pages. The basic functions can be achieved without knowing much PHP.