This is a very basic PHP class that I am working on which will allow me to provide an HTML template in the form of a string saved to a variable or into an actual template file. I can then pass into my PHP class an array where the array KEYS will be used to find and replace variables in the template HTML.
The template will define variables in this format {{first_name}}
, so my PHP array would have a key
of first_name
and its value
would be parsed into the final result HTML.
Example PHP array used to set and replace variables in the templates HTML...
$emailValues = array( 'first_name' => 'Jason', 'last_name' => 'Davis' );
This PHP array would then find and replace all occurrences of {{first_name}}
with Jason
and {{last_name}}
with Davis
I have coded this functionality into countless projects over the years but I generally have defined every single variable that get replaced in the template manually.
Purpose
I wanted a reusable method of doing this and even better, the flexibility to not have to define what variable are allowed in a template. With this class I can now use it in any project and use any variable I want in a template with {{varName}}
instead of being confined to a list of variables. It can now have unlimited variables and I don't have to manually set each one up. Simply call the variable in my template and assign a matching KEY
name in my PHP array of replacement values. I love the concept of it!
PHP Email Template Parsing Class
<?php /** * Email Template Parser * * Create HTML email body while replacing variable placeholders with content using a PHP ARRAY. * @package * @author Jason Davis * @version 1.0 * @copyright 2015 */ class EmailParser { protected $_openingTag = '{{'; protected $_closingTag = '}}'; protected $_emailValues; protected $_emailTemplate; protected $_isTemplateFile = false; /** * Email Template Parser Class * @param array $emailValues ARRAY where the KEY is the Variable name in the template and the VALUE is the replacement value. * @param string $emailTemplate HTML template string OR File path to a Email Template file. * @param boolean $isTemplateFile Optional - (Default: FALSE) - If set to TRUE, $emailTemplate is expected to hold the HTML template string. If set to FALSE, $emailTemplate is expected to be a File Path to external file containing email template string. * @return string HTML with any matching variables {{varName}} replaced with their values. */ public function __construct($emailValues, $emailTemplate, $isTemplateFile = false) { $this->_emailValues = $emailValues; $this->_isTemplateFile = $isTemplateFile; if($this->_isTemplateFile){ // Template HTML is stored in a File try { if(file_exists($emailTemplate)){ $this->_emailTemplate = file_get_contents($emailTemplate); }else{ throw new Exception('ERROR: Invalid Email Template Filepath'); } } catch(Exception $e) { echo $e->getMessage(). ' | FILE: '.$e->getFile(). ' | LINE: '.$e->getLine(); } }else{ try { // Template HTML is stored in-line in the $emailTemplate property! if(is_string($emailTemplate)){ $this->_emailTemplate = $emailTemplate; }else{ throw new Exception('ERROR: Invalid Email Template. $emailTemplate must be a String'); } } catch(Exception $e) { echo $e->getMessage(). ' | FILE: '.$e->getFile(). ' | LINE: '.$e->getLine(); } } } /** * Returns the Parsed Email Template * @return string HTML with any matching variables {{varName}} replaced with there values. */ public function output() { $html = $this->_emailTemplate; foreach ($this->_emailValues as $key => $value) { if(isset($value) && $value != ''){ $html = str_replace($this->_openingTag . $key . $this->_closingTag, $value, $html); } } return $html; } }
Example Usage using a variable to hold the Email Template HTML
$emailTemplateInline = <<<HTML <html> <body> <h1>Account Details Using Inline Template</h1> <p>Thank you for registering on our site, your account details are as follows:<br> Username: {{username}}<br> Password: {{password}} </p> </body> </html> HTML; $emailValues = array( 'username' => 'My username value here', 'password' => '' ); $emailHtml = new EmailParser($emailValues, $emailTemplateInline, false); echo $emailHtml->output();
Example Usage using an external File to hold the Email Template HTML
$emailTemplate = 'email-template.tpl'; $emailValues = array( 'username' => 'My username value here', 'password' => '' ); $emailHtml = new EmailParser($emailValues, $emailTemplate, true); echo $emailHtml->output();
email-template.tpl
<html> <body> <h1>Account Details Using External Template File</h1> <p>Thank you for registering on our site, your account details are as follows:<br> Username: {{username}}<br> Password: {{password}} </p> </body> </html>
Room for improvement
There is always room for improvement and 100 different ways to get your outcome when it comes to programming. With that said, I would like to hear some preferred ways of improving this very basic script.
This code works just fine so far in my testing but I always feel things can be improved and I do plan to use this across several large scale projects in the future so I want to identify and fix/improve any possible issues now if I can before it arises and issue once running on a live app!
To make it a little more flexible I decided to not require the Template HTML to be in an actual external template file. So now as an option, it can be a template file or else a string stored in a variable for more smaller 1 file type projects.
Another thing I tried to deal with is when a {{varName}}
variable placeholder is in the template but does not have a matching PHP array value. For this I am simply doing if(isset($value) && $value != ''){}
in the loop that is looking for placeholders in the template. I am sure there might be some better clever method.
It would be really cool if I could possibly have optional error mode which could build an array of any missing variables that are not being set and print that out to show that these variables are not being passed into the array.
I am mainly looking for you input for:
- Improvements to any of the code sections
- Ideas for additional settings and features