views:

518

answers:

4

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:

  1. import the template into my php that sends the mail
  2. find the div with a "content" class and add the submitted text into it
  3. send mail

but i don't know how to "find" that div and write the submitted text into it.

+2  A: 

Use str_replace() to insert the content into your template.

Use a class like PHPMailer to easily send HTML E-Mails.

Pekka
+3  A: 

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, ...);
brianreavis
+5  A: 

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.

Dan Breen
+1 PHP is a templating language, might as well take advantage of it. You still need `htmlspecialchars` though.
bobince
A: 

If you would like to avoid using placeholders or PHP code inside your template you could have a look at phpQuery, which is a PHP port of jQuery.

In your example you would something similar to this (see the docs):

<?php
$body = 'The body of your email message';

$template = file_get_contents('template.html');
$email = pq('div.content').html($body);
?>

Might seem a bit overkill but if you intend to add more of the same CSS selector based features, og simply want to get your designers' filthy hands off the PHP it might be a good solution.

phidah