Using Templates with PHP

Using templates in PHP can make complex tasks easier.  The template is the basic layout of your document. It contains placeholders for snippets of data that can be swapped into the template.  Here is some code to generate a sample template.

 Dear [+persons_name+],

I Am please to announce that you have just won a [+prize_name+]!
 You may Claim your Prize by visiting our [+office_name+] office.

 A Lottery.
$my_template = ob_get_clean();

You can see we are building emails to inform people of their lottery winnings. The placeholders are the items that begin and end with the [+ +] codes.

Next, we need to create an array of placeholder values we want to apply to the template. We can define the placeholders in an associative array:

$my_placeholders = array( "persons_name"=>"Benjamin",
                          "prize_name"=>"New Car",
                          "office_name"=>"Ottawa" );

Next, we need to create a function that will take the template, and our associative array of placeholders and put them together, returning the completed template.

function apply_template( $template, $placeholders ) {
     // create an array of all the [+placeholders+] in the template
     $matches = array();
     preg_match_all('~\[\+(.*?)\+\]~', $template, $matches);

     // loop through the placeholders and replace them with data
     foreach( $matches[1] as $id=>$match ) {
          $placeholder = isset( $placeholders[ $match ] ) ?
                                $placeholders[ $match ] : "";
          $template = str_replace( "[+" .  $match . "+]",
                                   $placeholder, $template );
     return $template;

Now we can create our final template by running the apply_template function on our template and placeholders:

$my_email = apply_template( $my_template, $my_placeholders );
Bookmark the permalink.

Comments are closed.