PHP’s variable interpolation works only in string literals. I want to develop a template mechanism which involves embedding variables into a text file, reading in the file, and then replacing the variables with their values.
I have 3 main methods:
The first is to use the PHP eval() function, together with a constructed Heredoc. The second is to use str_replace() over an array of variables. This has the advantage of allowing me to use my own notation for variables. The third is similar, except that it begins by reading what variables in the template are required.
Below is some sample code (first two methods only):
<?php
// Test File test.txt contains:
// $a plus $b gives $c etc
// $file=file_get_contents('test.txt');
// For testing, hard code:
$file=$file2='$a plus $b gives $c etc';
// Dummy data
$a=1; $b=2; $c=3;
// Template file can now be interpolated
// in a number of ways
// Method 1: use eval and constructed Heredoc
eval("\$file=<<<END\n$file\nEND;\n");
print $file;
// Method 2: use str_replace and $variables array
// ($variables will default to $GLOBALS, but can
// be any array of variable names);
// This will read from available variables into
// the string.
function interpolate2($text,$variables=null) {
$variables=$variables ? $variables : $GLOBALS;
foreach($variables as $variable=>$value)
if(strstr($text,"\$$variable")) $string=str_replace("\$$variable",$value,$text);
return $text;
}
print interpolate2($file2);
?>
I like the first because it is very simple. The question is, can anybody see any problems with either approach?
Thanks,
Mark