I’m trying to start using templates in my scripts, however I have problems looping through the variables in my template.
I’ve created a simple template script and my problem is that it only replaces 1 of my variables instead of all of them. If I use .= the problem persist ( I only replace 1 variable at the time). Could anyone help me with the logic of my script?
My PHP
<?php
$data= array('uno'=>'1','dos'=>'2','tres'=>'3','cuatro'=>'4','cinco'=>'5');
function tpl ($data,$tpl = null) {
foreach ( $data as $find => $replace ) {
$return = str_replace('{'.$find.'}',$replace,$tpl);
}
return $return;
}
echo tpl($data, file_get_contents('tpl.tpl'));
?>
My HTML template
<html>
<h1>{uno}</h1>
<h2>{dos}</h2>
<h3>{tres}</h3>
<h4>{cuatro}</h4>
<h5>{cinco}</h5>
</html>
Simple problem, you always start over the replace within
$tpldata. Always rewrite the variable content: