Basic HTML Template System in PHP

Basic HTML Template System in PHP

If you’re using PHP to send emails, either using the mail() function or perhaps using PHPMailer you’ve probably passed HTML data, including php variables directly into a parent $message variable, like so:

$to = "[email protected]";
$subject = "New contact form submission!";

$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>You have received a new message from your website!</p>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Message</th>
</tr>
<tr>
<td>" . $name . "</td>
<td>" . $email . "</td>
<td>" . $phone . "</td>
<td>" . $message . "</td>
</tr>
</table>
</body>
</html>
";

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <[email protected]>' . "\r\n";

mail($to,$subject,$message,$headers);

But what if there was a more elegant solution that didn’t require clogging up your php file with html output? Thankfully, it’s not all that complicated to move this html email content into an unsophisticated email template-style system.

First, you’ll want to create an associative array to hold the variables you’ll be passing into the HTML file (after sanitizing them of course!). In this example we going to put the captured $_POST variables from a contact form into an associative array named $email_var. Then we’re going to loop through the array and place the variables inside the email template.

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

$email_var = array();
$email_var['name'] = $name;
$email_var['email'] = $email_address;
$email_var['phone'] = $phone;
$email_var['message'] = $message;
$template = file_get_contents("default_template.html");
foreach($email_var as $key => $value) {
$template = str_replace('{{ '.$key.' }}', $value, $template);
}
$email_body = $template;

And lastly, you’ll want to create your html template file, in this example it is named “default_template.html” and is located in the same directory of the php file referencing it. It looks something like this:

<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Message</th>
</tr>
<tr>
<td>{{ name }}</td>
<td>{{ email }}</td>
<td>{{ phone }}</td>
<td>{{ message }}</td>
</tr>
</table>
</body>
</html>

And that’s it! Of course that is just the tip of the iceberg … you could create different HTML email templates and call on them based on values submitted in the form. For example:

if ($this === true) {
$template = file_get_contents("default_template.html");
} else {
$template = file_get_contents("some_other_template.html");
}

Enjoy!