Jump to content

[SOLVED] External email text file template with variable interpolation


Helmet

Recommended Posts

I'm looking at this problem for the first time and wondering the best way to approach it. I have to create a couple of editable text files containing the contents of an auto generated email for my client's site. They want to be able to edit it, which is why I want to put the content in a text file which would be processed and then sent to the mail script, like PHPMailer or Swiftmailer.

Example:

 

automail.txt

--------------------------

Hello %first_name%,

Thank you for your interest in %product_name%. A sales associate will contact you shortly.

Sincerely,

etc etc

 

Is there an established "right way" to do this? I've been looking for information using keywords "text file interpolation php" but finding only general variable interpolation in code, not like this type of basic template stuff. I might not be searching on the right keywords. I have looked at eval, but I wouldn't want to rely on php variables with dollar signs since at some point when they're editing the template they could add one to the content and break the script.

 

How should I be approaching this, or does anyone know of a good place to find an example?

you could use your current example, and do something like this:

 

template.txt:

Hello %first_name%,
Thank you for your interest in %product_name%. A sales associate will contact you shortly.
Sincerely,

 

form_process.php

<?php
$first_name = "John";
$product_name = "The UltraWahoo";
$to = "[email protected]"
$fh = fopen("template.txt", "r");
$data = fread($fh, filesize("template.txt"));
fclose($fh);
$new_body = str_replace("%first_name%", $first_name, $data);
$new_body = str_replace("%product_name%", $product_name, $new_body);
//do your mail stuff here
mail($to, $subject, $new_body);
?>

Thanks for your reply

 

I ended up doing it like this:

 

mail_template.txt:

Hello {first_name},
Thank you for your interest in {product_name}. A sales associate will contact you shortly.
Sincerely,

 

process.php:

//$_POST variable names from form are same as variable names in curly braces in template.txt
$input = file_get_contents('mail_template.txt');
$output = preg_replace('/\{(\w+)\}/e',"\$_POST['\\1']",$input);
//send output to mail script

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.