Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 147 ยท PHP and the Web

PHP and HTML Templates

Embed PHP in HTML the clean way - short echo tags, alternative syntax, escaping with htmlspecialchars, template files with output buffering and layouts.

PHP was born as a tool for putting dynamic bits into web pages, and it's still the only mainstream language where an HTML file can simply become a program by adding a few tags. A .php file is copied to the output as-is, except for the parts between <?php and ?>, which run as code. That makes PHP a template language out of the box: no extra library is needed to print a list of products into an HTML table.

That power is easy to misuse. Code that mixes database queries, business rules and HTML in one file was the norm for years, and it's hard to read, hard to test and full of security holes. This lesson shows the modern way to combine PHP and HTML: short echo tags and the alternative control-structure syntax for readable templates, escaping every value with htmlspecialchars(), rendering separate template files with output buffering, and keeping logic out of the views.

A note on our editor: it runs PHP on the command line, so HTML your code produces appears as source text in the output panel. On a web server the same output is sent to the browser, which renders it as a page.

Mixing PHP into HTML

Everything outside PHP tags is inline HTML, and PHP sends it to the output unchanged. You can switch in and out of PHP as often as you like, even in the middle of a loop. The short echo tag <?= $value ?> is shorthand for <?php echo $value; ?> and is always available (it doesn't depend on the short_open_tag setting, unlike the old <? tag, which you should never use).

PHP A page with embedded PHP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The code before the HTML prepares the data, and the HTML part only prints it. The loop opens with <?php foreach (...) { ?>, repeats the inline <li> line for each book, and closes with <?php } ?>. (The date('H:i', 0) call formats the timestamp 0, so the example prints the same output every time.)

This example skips one essential step, escaping, to keep the first look simple. We'll fix that in a moment.

The newline after ?>

Look closely at the output: the lines with only <?php foreach ... ?> and <?php } ?> leave no blank lines behind. PHP swallows one newline directly after a closing ?>. That's convenient for lines that hold only a control structure, but it applies to <?= ... ?> at the end of a line too, which can glue that line to the next one in the output. If you see lines unexpectedly joined in generated HTML, this is why; ending such a line with an HTML tag instead (as the <li> lines above do) avoids it. The rule is convenient in templates, and it's also why a file containing only PHP code should not end with ?>: any extra blank line or space after it would be sent to the browser, which can break HTTP headers or file downloads. The PHP Syntax lesson covers the closing-tag rule.

Alternative syntax for templates

Braces get lost in HTML: when a template has a } on its own, it's hard to tell which block it closes. PHP has an alternative syntax for control structures that reads better in templates. Replace the opening brace with a colon and the closing brace with an end keyword:

Normal Alternative
if (...) { ... } elseif (...) { ... } else { ... } if (...): ... elseif (...): ... else: ... endif;
foreach (...) { ... } foreach (...): ... endforeach;
for (...) { ... } for (...): ... endfor;
while (...) { ... } while (...): ... endwhile;
switch (...) { ... } switch (...): ... endswitch;
PHP Alternative syntax in a template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each endif; and endforeach; says exactly what it closes. Use the alternative syntax in templates and normal braces in plain PHP code; mixing both styles in one block is a syntax error. The ternary inside the class attribute is a handy way to switch small values; see Null Coalescing, Ternary and Nullsafe Operators.

Escaping output with htmlspecialchars()

Every value you print into HTML must be escaped. If a book title or a user's comment contains <, >, & or quotes, the browser interprets them as markup. When the value comes from a user, that's a security hole called cross-site scripting (XSS): an attacker submits a "name" like <script>...</script>, and your page runs their code in every visitor's browser.

htmlspecialchars() converts the five special characters into HTML entities, so the browser shows them as text:

Character Becomes
& &amp;
< &lt;
> &gt;
" &quot;
' &#039;

Since PHP 8.1, the default flags are ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, so both quote types are escaped and invalid UTF-8 is replaced instead of producing an empty string. The default charset is UTF-8. Writing a short helper function keeps templates readable:

PHP Escaping values in a template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the unsafe version, the comment would run a script, and the double quote in the website breaks out of the href attribute to add an onmouseover handler. In the safe version, every special character became an entity. Escaping is what makes both attacks harmless.

Some rules to remember:

  • Escape at output time, in the template, not when you save data. The same value may go into HTML, JSON or an email, and each needs different escaping.
  • Always quote attributes with double quotes. An escaped value in an unquoted attribute (<input value=<?= e($v) ?>>) can still be broken by a space.
  • htmlspecialchars() is correct for HTML text and quoted attributes. A URL in an href also needs its scheme checked (a javascript: URL is dangerous even when escaped), and values inside <script> blocks need json_encode() instead. Preventing XSS covers every context.

From here on, every example that prints HTML escapes its values. Real projects usually let a template engine do this automatically: Laravel's Blade escapes everything inside {{ }}, and Twig escapes by default too.

Template files and output buffering

In a real application, each page's HTML lives in its own template file (often called a view), such as templates/product.php. The controller code gathers data and asks a render function to fill in the template. The trick that makes this work is output buffering:

  • ob_start() starts capturing output instead of sending it.
  • Anything echoed afterwards, including inline HTML in an included file, goes into the buffer.
  • ob_get_clean() returns the captured text as a string and stops buffering.

So a render function can include a template and return its output as a string, which you can print, put inside a layout, cache or send in an email. The example writes template files to the temporary folder first, since our editor runs a single file; in a project they'd be normal files in a templates/ folder.

PHP A render function with output buffering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

How the pieces fit:

  • render() runs the template inside a function, so the template only sees the variables you passed (plus its own). extract() turns the array keys into local variables; it's normally a function to avoid, because it can silently overwrite variables, but in this tiny, controlled scope with EXTR_SKIP it's the standard trick. The $path and $template variables can't be overwritten thanks to EXTR_SKIP.
  • The layout contains the shared page frame, and <?= $content ?> prints the already-rendered (and already-escaped) inner HTML. That's the one place where a value is printed without e(), because it's HTML we produced ourselves.
  • If a template throws an exception, ob_end_clean() throws away the partial output so a broken half page is never mixed into the response. Leaving buffers open is a common source of confusing output.

Output buffering has other uses too: capturing the output of a function that only knows how to echo (like var_dump()), and making sure nothing is sent before you call header(). ob_get_level() tells you how many buffers are currently open.

Separating logic from views

The rule that keeps templates maintainable: a template only displays data. It may loop, branch on simple conditions, format numbers and dates, and escape. It must not query the database, read $_POST, change state, or contain business rules. Those happen before rendering, in plain PHP code.

Compare two versions of a product list:

PHP
<!-- Hard to maintain: logic, data access and markup all in one file -->
<ul>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'shop', 'secret');
foreach ($pdo->query('SELECT * FROM products') as $row) {
    if ($row['stock'] > 0 && $row['hidden'] == 0) {
        $price = $row['price'] * 1.2;   // VAT? discount? nobody remembers
        echo '<li>' . $row['name'] . ' ' . $price . '</li>';
    }
}
?>
</ul>

The improved version moves the decisions into a function that's easy to test, and the template gets only what it needs to show:

PHP Logic first, then a dumb template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

visibleProducts() holds every business rule (what's visible, how VAT is applied, what "low stock" means), works on prices in integer cents, and returns plain arrays. You could unit-test it without any HTML. The template underneath only loops, branches and escapes. This split is the core idea behind MVC, which you'll meet again in Front Controllers and Routing and PHP Frameworks and CMSs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is <?= $title ?> equivalent to?

    The short echo tag prints the expression. It is always available, unlike the old <? short open tag.
  2. 2. Which line correctly closes a block opened with <?php foreach ($items as $item): ?>?

    The alternative syntax pairs foreach (...): with endforeach;. Using a brace to close a colon block is a syntax error.
  3. 3. A user enters the name <b>Bo</b>. What does htmlspecialchars('<b>Bo</b>') return?

    The angle brackets become entities, so the browser displays the tags as text instead of making the name bold. The last option is URL encoding, which is a different thing.
  4. 4. Inside a render function, what does ob_get_clean() do?

    ob_start() begins capturing; ob_get_clean() returns what was captured and closes the buffer, so render() can return the HTML instead of printing it.
  5. 5. Which of these belongs in a template file?

    Templates should only display data that was prepared before rendering. Queries, request handling and business rules go in plain PHP code that runs first.

Summary

  • Text outside PHP tags is sent unchanged; <?= expr ?> prints a value; PHP eats one newline right after ?>, and pure PHP files should omit the closing tag.
  • In templates, use the alternative syntax: if: ... elseif: ... else: ... endif;, foreach: ... endforeach; and friends.
  • Escape every value printed into HTML with htmlspecialchars() (a short e() helper keeps templates tidy), always quote attributes, and escape at output time.
  • Output buffering (ob_start() + ob_get_clean()) lets a render() function return a template's output as a string, which makes layouts possible.
  • Keep logic out of views: prepare data in plain PHP functions, then pass it to templates that only loop, branch, format and escape.

Next: Superglobals