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.
I am a developer and I know how hard it is to solve difficult issues while programming in case you did not get any help. I have faced this so many times. That's why I started this blog so that I can share problems and solutions with developer community. In case if you face any issue in programming do check my blog once, it will surely save your time.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment