home |  
Sell Downloads - Ejunkie
open db network by 19.5 degrees
LYRICS | FREE E-BOOKS | SELL DOWNLOADS WITH PAYPAL
 in   
contribute for fun & profit
brink
-Parsing PHP..
-Misc. Tutorials..
-Pixel art..
-Windows..
 
See all Tutorials
 
All Resources > Tutorials > PHP
spread the word around  send this page to a friend   read/write comments/corrections/additions comments  rate this 

Parsing PHP

by 19.5 Degrees
 
 
views: 8057 | rating: 5/10
 


Sometimes you want to keep your code separate from your design. This is where templating comes in. This does not necessarily mean that you have to use a 3rd party templating solution and learn an entirely new command set. You can simple achieve your objective taking advantage of the php parser itself and thus all the native php functionality will be available to you. It is up to judgment that you should not put too much code in the template file and only as much as it might be required for design related decisions. For example, using alternate colors in table rows or showing a section only if a particular variable is true.

NOTE: If you are here just to see how parse php (using eval) in a string without using complex back tracking of preg_replace, click here.

Now, we'll use two files

1. code.php
2. template.tpl


Usually your code.php will interact with database and populate the variables. For example, if your code file (without the design) currently looks like

<?
$data=array();

$resultset=mysql_query("SELECT user_firstname, user_lastname FROM user_table;");

$i=0;
while ($row=mysql_fetch_assoc($resultset)) {
    // arrayToArrayVars function reates and populate globally accesible arrays with the same names as the columns of result set
    // in this case, it'll return 2 arrays $user_firstname & $user_lastname

    arrayToArrayVars($row,$i);
    $i++;
}

// arrayToArrayVars function creates and populates globally accesible arrays with the same names as the columns of resultset

function arrayToArrayVars($array,$index) {
    foreach ($array as $key=>$value) {
        if (getType($key)=="string") {
            eval("global \$$key;");
            eval("\$$key"."[$index]"."=\$value;");
        }
    }
}

?>

All you have to do is to append the following lines of code at it's end

<?

    // open the template file and read it into a variable $php
    $fp = fopen ("template.tpl", "r");
    $php = fread ($fp, filesize ("template1.php"));
    fclose ($fp);

    // turn on output buffering
    ob_start();
    // this parses the php code in out $php variable; this is the heart of our templating logic
    eval(" ?>" . $php . "<? ");
    // store the final parsed output in a variable $output
    $output = ob_get_contents();
    // clear buffer and stop buffering
    ob_end_clean();

    // this line show the parsed final data in the browser
    echo $output;

?>


Now, your template file will be a regular HTML file and it can have ANY php commands in it. I'll give you an example of a template which will show table with alternate colored rows and it'll show table only if the array $user_firstname has any values.

<html>
<head><title>template.tpl</title></head>
<body>

<? if (sizeof($user_firstname)>0): ?>
  <table> 
      <?
        for ($i=0; $i<sizeof($user_firstname); $i++) {
            // (($i/2)==round($i/2)) check whether $i is even or odd
            echo "<tr bgcolor=\"".((($i/2)==round($i/2))?"#EEEEEE":"#FFFFFF")."\"> ";
            echo "<td >".$user_firstname[$i]."</td><td>".$user_lastname[$i]."</td>";
            echo "</tr>";
        }
    ?>

  </table>
<? endif; ?>
</body>
</html>


NOTE: You template file should be have all the php within valid php tags.


Following section is just for people who are interested in knowing how parse php (using eval) in a string without using complex back tracking of preg_replace.

<?

    // php is
    $php = "this is the text with php code in it. right now date & time is <? echo date ("l dS of F Y h:i:s A"); ?>";
  
    // turn on output buffering

    ob_start();
    // this parses the php code in out $php variable; this is the heart of our templating logic
    eval(" ?>" . $php . "<? ");
    // store the final parsed output in a variable $output
    $output = ob_get_contents();
    // clear buffer and stop buffering
    ob_end_clean();

    // this line show the parsed final data in the browser
    echo $output;

?>

 




« PREVIOUS
  INDEX
NEXT »

spread the word around
read comments

nice trick with eval..
posted by: Said
on: Sep 6, 07 9:37 am

Hey, Author..

Just wanted to let you know how much I appreciate your "Parsing PHP." article you wrote waaaaaaaaaay back..

that trick (however unsafe it might be) is quite well done...
I was looking for an easy way.. and this certainly is..

Thanks

post reply | read replies (0)



Thanks
posted by: abyssalnightmare
on: Mar 30, 05 8:06 am

Nice tutorial. Very helpful.

post reply | read replies (0)



read more commentspost comment 



home | contact | contribute | terms of use | privacy policy |