How to create and use templates in PHP

Hello,

This blog is for freshers in PHP.

First of all why Templates?


Templates are for reusable piece of code.  Consider an example. You have to send mail on some events and all the events are being invoked on different pages. However mail content is always same only some values are changed like sender name and sender signature etc. So instead of building message body every time you build a reusable templates that can be used by simply replacing some values in it. Another advantage of templates is you just need to change only templates and changes are visible at every place where template is used. Email template is just an example you can also build dynamic websites using templates. Here in this blog I will give example of email templates. So let’s start our example.

First of all create an HTML file for your mail message with following syntax.

<div style=”width: 800px;”>

<span>Hello </span><span>%%client_full_name%%</span><br />
<span>%%email_introduction_text%%</span><br />

<b> Thank you for your query, we will get back to you soon</b>

<span>%%sales_rep_name%%</span><br />
<span>%%sale_rep_phone_num%%</span><br />
</div>

If you carefully check above HTML all the variables enclosed in %% %% are the variables which will be replaced by values dynamically when you use mail template. Following is the code for it.

First of all build an array with all the variable names as a key and with their values.

$variablesArray=array(
   ‘%%client_full_name%%’=>$clientName,
   ‘%%email_introduction_text%%’=>$emailIntroductionText,
   ‘%%sales_rep_name%%’=>$salesRepName,
   ‘%%sale_rep_phone_num%%’=>$sale_rep_phone
   );

Now read the mail template file and replace all the variables with respective values.

$myFile = “mail_template.html”;

$fh = fopen($myFile, ‘r’);
$body = fread($fh, filesize($myFile));
fclose($fh);
       
foreach($variablesArray as $variable=>$value)
{
         $body=str_replace($variable,$value,$body);
}

That’s it $body will have all the values replaced now and you can use this while sending mail. This way you can also build dynamic website also.

Hope this post helps you.

This entry was posted in Uncategorized on by .

About Hiren Dave

Hiren Dave is a software engineer, blogger and consultant with over 9 years of professional experience. He writes code in number of languages. Hiren has a passion for developing web apps, mobile apps and writing books and blog articles about programming. He has a solid experience of startups as he manages products for few startups. He is also passionate about researching and learning new technologies and trends. He has also authored a book Instant Sencha Touch, published by Packt and creator of Video Course "Beginning Laravel" for Packt

Leave a Reply

Your email address will not be published. Required fields are marked *