PHP html email, using html template
Solution 1
As Pekka was saying, you could simply use str_replace
to insert data in your template. Just add a placeholder:
<div clas="header"></div>
<div class="content">{{content}}</div>
<div class="footer"></div>
Then replace the placeholder with your content:
$content = 'Whatever you want to insert...';
$tpl = file_get_contents('yourtemplate.html');
$tpl = str_replace('{{content}}', $content, $tpl);
mail($tpl, ...);
Solution 2
You could put a PHP script inside the template and then have PHP itself do the rendering, for example:
template.html:
<div clas="headr"></div>
<div class="content"><?php echo $body; ?></div>
<div class="footer"></div>
Then to load it, in your PHP code:
$body = "Put this into the content tag...";
ob_start();
include("template.html");
$email = ob_get_clean();
Edit: in this case it's perhaps a bit overkill to use my method instead of a simple replace, but if instead of replacing the entire email message you wanted to have a more complicated template, it makes it easy. E.g.:
<table>
<tr>
<td>Name:</td>
<td><?php echo $name; ?></td>
</tr>
<tr>
<td>Email:</td>
<td><?php echo $email; ?></td>
</tr>
</table>
It's very flexible and prevents having to have too many variables to replace, and more importantly keeps html out of your code.
Solution 3
Use str_replace() to insert the content into your template.
Use a class like PHPMailer to easily send HTML E-Mails.
Solution 4
Please, find out the wide answer at Programmers.StackExchange which includes different approaches on PHP email templating.
The simple PHP solutions can be:
- usage of simple
%placeholder%
replacement mechanisms:-
str_replace
, -
preg_replace
(works great witharray
replacements)
-
- simple PHP templating and conditional logic (short open tags in PHP and alternative syntax for control structures)
kmunky
Updated on June 09, 2022Comments
-
kmunky almost 2 years
so i'm trying to do a do a html mail sytem and my html i want to be a template, stored in a separate file like :
<div clas="headr"></div> <div class="content"></div> <div class="footer"></div>
when i want to send the mail i want my mail content(from the input form) to go in that div.content and then to send the whole html(template + submitted text). what is the best way to do that? i'm thinking to something like:
- import the template into my php that sends the mail
- find the div with a "content" class and add the submitted text into it
- send mail
but i don't know how to "find" that div and write the submitted text into it.
-
Amit Patil over 14 years+1 PHP is a templating language, might as well take advantage of it. You still need
htmlspecialchars
though.