PHP
  Home arrow PHP arrow Page 5 - Building a Template Parser Class with ...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Building a Template Parser Class with PHP, Part I
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 69
    2005-03-22

    Table of Contents:
  • Building a Template Parser Class with PHP, Part I
  • PHP: The first templating system available
  • Defining the structure of the PHP class
  • Completing the class: the "parseFile()" and "display()" methods
  • Implementing the class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Building a Template Parser Class with PHP, Part I - Implementing the class


    (Page 5 of 5 )

     

    Before we see how the class is practically implemented, let’s see the complete source code. Here’s the listing:

     

    class templateParser {

        var $output;

        function templateParser($templateFile='default_template.htm'){

              (file_exists($templateFile))?$this-
    >output=file_get_contents($templateFile):die
    ('Error:Template file '.$templateFile.' not found');

        }

        function parseTemplate($tags=array()){

              if(count($tags)>0){

                   foreach($tags as $tag=>$data){

                        $data=(file_exists($data))?$this-
    >parseFile($data):$data;

                        $this->output=str_replace
    ('{'.$tag.'}',$data,$this->output);

                   }

              }

              else {

                   die('Error: No tags were provided for replacement');

              }

        }

        function parseFile($file){

              ob_start();

              include($file);

              $content=ob_get_contents();

              ob_end_clean();

              return $content;

        }

        function display(){

              return $this->output;

        }

    }

     

    Finally, here’s a possible real implementation for the class:

     

    <?php

    // include the class

    require_once('template.php');

    // instantiate a new template Parser object

    $tp=&new templateParser('template.htm');

    // define parameters for the class

    $tags=array('title'=>'You are seeing the template parser class in action!','header'=>'header.php','navbar'=>
    'navigation bar.php','leftcontent'=>'leftcontent.php',
    'maincontent'=>'maincontent.php',
    'rightcontent'=>'rightcontent.php',
    'footer'=>'footer.php');

    // parse template file

    $tp->parseTemplate($tags);

    // display generated page

    echo $tp->display();

    ?>

     

    The above code is really easy to follow. First, I include the proper class file. Then a new template parser object is instantiated, specifying a "template.htm" file as the template to be parsed.

     

    Please note that I’m instantiating the object with the (&) ampersand operator, which means that I’m working with a reference of the object, not a copy. This is necessary in PHP4 for specifying the behavior when we’re instantiating objects. Fortunately, in PHP 5, the default behavior is working with object references.

     

    Next, I define an array structure containing the parameters to be passed to the class. In the example, I’ve chosen a string for page title, and several PHP files for generating the different sections of the page. As you can see, the class offers the possibility to include dynamic or regular content. 

     

    Finally, the object invokes the "parseTemplate()" method, which will replace the placeholders with the real values contained in the "$tags" array. Once the template is processed, the "display()" method is called, displaying the generated page. Here, it becomes clear that instead of directly echoing page contents, we might, for instance, send the page via email. Doing so makes the class much more flexible.

     

    Summary

     

    Are you still with me? Okay, we have finally created a simple but extensible class for parsing template files with no major headaches. What’s more, the code is easily portable to PHP 5 with minor modifications. However, the job is not completely done. In the second part of this article, I’ll add some caching capabilities to the original class, increasing its current functionality. In the meantime, feel free to play around with the code and think about possible improvements. I'll meet you in the second part!  


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · Definitively, building a small template system is easy with PHP. Hopefully...
       · True... the article showed how easy it is to create sucha sistem..howevere these...
       · Since the class was introduced as a simple template parser, the addition of new...
       · The only things I see an immediate need for are a way to handle repeating fields...
       · Unfortunately, those possible additions are not implemented in part II. I only...
       · While I appreciate your approach, I can see an issue. I understand what I want it...
       · Hello friend,I get your point about a template system. It's truly desirable...
       · Yes, if I could only get the swedish characters å ä ö Å Ä Ö to be displayed...
       · According to your needs, you should include the charset ISO-8859-1 into the head...
       · Thanks for the fast reply!! :-)I added the meta-tag. And I also added some code,...
       · I'm glad you found a solution for the problem.Just one advice: whenever you can,...
       · one comment: mixing html and php is not a problem!!! replacing <?= $var => by {$var}...
       · Thank you for pointing that nice article. Sure it's very valuable for any web...
       · Wonderful simple looking template parser; Your explanation is very understandable,...
       · Hi friend,I'm glad you liked the article. Of course I've no problem sending some...
       · I was wondering how you would use this template system when you want different...
       · It's easy to create different pages with the same template file. This way, you're...
       · It's easy to create different pages with the same template file. This way, you're...
       · Im fairly new to PHP and only know the basics of it. Im not sure how this could be...
       · Yes, I see your point. Here´s a possible solution.First, perform your queries, and...
       · Yes thats what I want to do but as you said.. build it into a variable for example...
       · Hello, here's your solution:// initialize your output...
       · I´m really glad I´ve been monitoring this discussion. This while-loop is just what...
       · Hey, I'm glad you found it useful for your needs. Thank you for the kind words and...
       · Just learning about classes. I tried to use your code, but it didn't work. I did a...
       · Hello, I found the error in your code. You listed the following:foreach($tags as...
       · Stunning class first of all. Very clear, very helpful and very practical.Now the...
       · Thank you for giving your opinions about the class.Regarding your question, it´s...
       · Thanks for getting back, so swifthly too.I agree that adding the conditionals to...
       · Forgot to add:The template is thus:{header}{login-box}{leftbox}
       · Thank you for the kind words.I think this is what you're looking for:First,...
       · Perfect solution.Thanks again.Like many others it seems, I'd love to see a...
       · Nice to hear it was the solution for your problem.About Part III, I hope to find...
       · All going really well. Then I added a template which includes: if...
       · Hello friend,I hope this helps. In first place when we're talking about a...
       · Damn. You've pretty much said what I was hoping you wouldn't -- that being that it...
       · Oddly, I've just noticed that if I reinstantiate the class within the tpl-footer...
       · I guess I found the error. I will try to keep it short, so spiders won't index much...
       · No, sadly that's not the answer. I should have perhaps mentioned, the init.inc.php...
       · hi everybodyhow i can build my database by php parsing . i mean that i wanna...
       · There are several ways to update your database, even in that given short time. One...
       · Hi there could the author possibly email me at liamdawe@gmail.com and help me out a...
       · Hello,I've emailed you at the given address. Thanks!
       · is it any way i can get info from mysql into a {something}? like:'cat' => ...
       · About your question, I think that the best way to include query resources is first...
       · thank you!now i have another problem :(it works when i just print out 2 things...
       · Generally, and depending on the configuration file, PHP access files by using the...
       · Very nice class indeed, simple, basic and yet very powerfull!However, i`m trying...
       · Thanks for the comments on the class. Now, let's point to your...
       · Thank you for the quick reaction, and also the good example. I think I can match...
       · You're welcome. I'm glad to know the answer was helpful.Regards.
       · i`ve extended the class with the option to parse {img}{/img} tags too, using the...
       · Nice class improvement. Adding image-parsing capabilities to the class' logic is a...
       · Another contribution for your nice class, the option to make hyperlinks out of tags,...
       · Excellent implementation of regular expressions. Also, trough regexp, another...
       · I wanted to be able to also parse functions and function arguments with the same...
       · Thank you for commenting on my PHP Template parser class article. I see that you...
       · Hello, I am trying to loop through a template file like so :There is two...
       · Thanks for the kind comments on my PHP article. In a case like this, where the...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT