Articles Html
PHP-HTML Templates: A New Working Relationship - Page 5
by: PHP Builder Staff
|
April 3, 2002
All the work will then be performed by the PHP function : template_parser.
The detailed workings of template_parser function is as follows :
function template_parser
function template_parser ($template_filename, $replacement_rules, $recordset_array)
{
$START_FLAG = 0;
$start_anchor=0;
$end_anchor=0;
$res_arr="";
$fcontents = file (TEMPLATES_PATH . $template_filename);
while (list ($line_num, $line) = each ($fcontents))
{
if ($START_FLAG == 0)
{
if (ereg ('<!--START_ROW-->', $line))
{
$START_FLAG = 1;
$start_anchor = $line_num;
}
}
else
{
if (!ereg ('<!--END_ROW-->', $line))
{
$res_arr .= $line;
}
else
{
$START_FLAG = 0;
$end_anchor = $line_num;
}
}
}
/* Build String-Replacement Rules ... */
$tmp_res_arr = "";
$n = count($data_array);
for ($x=0; $x<$n; $x++)
{
$tmp = $res_arr;
for ($y=0; $y<count($replacement_rules); $y++)
{
$a = $replacement_rules[$y][0];
$b = $replacement_rules[$y][1];
if (ereg ("<!", $a))
{
$data_array[$x][$b] = stripslashes ($data_array[$x][$b]);
eval ("\$tmp = str_replace (\"$a\", \$data_array[\$x][$b], \$tmp);");
$tmp = stripslashes($tmp);
}
}
$tmp_res_arr .= $tmp;
}
$res_arr = $tmp_res_arr;
/* Re-constructing the file-contents ... */
$n = count($fcontents);
for ($x=0; $x<$n; $x++)
{
$y = $start_anchor + ($x - $end_anchor) ;
if (($x >= $start_anchor) and ($x < $end_anchor))
{
if ($n_fcontents[$start_anchor] == "")
$n_fcontents[$x] = $res_arr;
}
elseif ($x > $end_anchor)
$n_fcontents[$y] = $fcontents[$x];
else
$n_fcontents[$x] = $fcontents[$x];
}
return ($n_fcontents);
} // end function template_parser
What the above does is to "reproduce" the HTML codes surrounded by both HTML-comment tags :
<!--START_ROW--> and <!--END_ROW--> as many times as the number of rows found in the $recordset_array array, yet with the intelligence to replace data fields (columns of $recordset_array array) in places
defined in the $replacement_rules array without affecting the original HTML formattings.
When all the necessary replacements have been done, the entire HTML page will be "echoed" out by PHP.
Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.