PHP and HTML

PHP and HTML Cycle

PHP and HTML interact a lot. PHP is a HTML pre-processor, which means it is designed to generate HTML. In turn, HTML can pass data and information PHP through HTTP requests (we will learn more about that later), which is then used to generate new HTML. This cycle is how dynamic HTML that tracks and follows a user is created.

Intertwine PHP and HTML

Many beginning PHP developers will try to keep PHP separate from HTML. While a noble pursuit, it is the wrong one. Because PHP will run on the server and the PHP compiler will only send HTML to the browser, it is possible and encourage intertwine the two.

<?php 
  $title = 'Hello Class';
  $language = 'PHP';
?>

<html>
  <body>
    <h1><?php echo $title; ?></h1>
    <p>Greetings from the world of <?php echo $language; ?>.</p>
  </body>
</html>

But we are not just limited to the just the output of variables. It possible to make HTML conditional or repeat HTML using PHP conditional statements and loops.

<?php 
  $title = 'Hello Class';
  $language = 'PHP';
?>

<html>
  <body>
    <h1>
      <?php if (isset($title)) : ?>
        <?php echo $title; ?>
      <?php else : ?>
        Hello World
      <?php endif; ?>
    </h1>
    <?php for ($i = 0; $i < 3; $i++) : ?>
      <p>Greetings from the world of <?php echo $language; ?>.</p>
    <?php endfor; ?>
  </body>
</html>

PHP Templates

In most multiple pages, there are elements that remain consistent from page to page, like the navigation or footer. If a change is required to one of these repeating elements, you must make the change on every page. This can take time and can lead to mistakes. This is where PHP templates come in.

By creating templates, it is possible separating the repeating content from the page-specific materials. These means change are needed, they only need to made in one place.

<?php /* Simple PHP Template */?>
<html>
  <body>
    <nav>...</nav>
    <?php if (isset($title)) : ?>
      <h1><?php echo $title; ?></h1>
    <?php endif; ?>
    <?php if (isset($content)) : ?>
      <main>
        <?php echo $content; ?>
      </main>
    <?php endif; ?>
    <footer>...</footer>
  </body>
</html>