How can PHP variables be properly set and utilized within HTML templates?

To properly set and utilize PHP variables within HTML templates, you can use PHP opening and closing tags to switch between PHP and HTML code. Assign your PHP variables their values before the HTML code that will display them. Then, within the HTML code, you can echo the PHP variable using the `echo` statement or directly embed the variable within the HTML code.

<?php
    $name = "John Doe";
    $age = 30;
?>

<!DOCTYPE html>
<html>
<head>
    <title>PHP Variables in HTML</title>
</head>
<body>
    <h1>Welcome, <?php echo $name; ?>!</h1>
    <p>You are <?php echo $age; ?> years old.</p>
</body>
</html>