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 />
<b> Thank you for your query, we will get back to you soon</b>
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.
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));
foreach($variablesArray as $variable=>$value)
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.
Saturday, July 16, 2011
How to create and use templates in PHP
Posted by Hiren Dave at 4:16 PM
CTO, Technology Author / Blogger / Speaker, Team Member GDG Ahmedabad
Subscribe to: Post Comments (Atom)
Post a Comment