Saturday, July 16, 2011

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.

No comments:

Post a Comment