0

I have a text file named myFile.txt with following content:

My variable is $myVar

PHP Example 1:

$myvar = "Parsed";
$a = file_get_contents("myFile.txt");
echo $a;

Result

My variable is $myVar

PHP Example 2:

$myvar = "Parsed";
$a = "My variable is $myVar";
echo $a;

Result:

My variable is Parsed

How can I make PHP to parse the variable $myVar in example 1, the way it is parsed in example 2?

Thank you

Thanasis
  • 329
  • 4
  • 8
  • `file_get_contents` reads the file. Nothing more. You could use `eval`, but it's evil if you don't use it with cautious. – Charlotte Dunois Sep 22 '16 at 22:18
  • Is there any reason why you can't use str_replace? – Craig Sep 22 '16 at 22:23
  • 1
    Thanks brothers. eval sounds cool ! why should I be cautious with it? In fact I want to use a text file with 100 variables. str_replace would be too slow I guess. – Thanasis Sep 22 '16 at 22:29
  • Read the warnings on the manual's page. `The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. `-http://php.net/manual/en/function.eval.php – chris85 Sep 22 '16 at 22:29
  • eval is giving error if string in .txt file is complicated or html or something. – Thanasis Sep 22 '16 at 22:37
  • The right solution is to use a real template library. – Barmar Sep 22 '16 at 23:10

2 Answers2

0

Using a mixture of RegEx and eval() would do the job.

myFile.txt

My variable is $myvar and another variable is $another

index.php

<?php

// vars
$myvar = "parsed";
$another = "whatever";

// regEx
$re = "/(\\$\\w+)/"; 
// string to search
$str = file_get_contents("myFile.txt");
// replacing the match
$subst = "<?php echo $1; ?>"; 

$result = preg_replace($re, $subst, $str);

eval('?>' . $result);

?>

Remember, eval() shouldn't be used for outputting variables / sensitive data / etc. Maybe you should consider using a template engine instead.

Another basic approach would be something like wrapping the variable names inside of curly braces or anything similar.

My variable is {{myvar}} and another variable is {{another}}

Heres the code to "render" it in a better way.

<?php

// data array of accessible keys
$vars = array(
  "myvar" => "Hello :)",
  "another" => "whatever"
);

// template
$tpl = file_get_contents("myFile.txt");

// replace key placeholder with assigned values
foreach($vars as $key => $val) {
  $tpl = str_replace('{{'.$key.'}}', $val, $tpl);
}

// output the template
echo $tpl;
?>

Hope this helps.

Kid
  • 36
  • 4
0

Another possibility is to ditch the txt file, replace it with a php file and just include that.

so myText.php file would be:

My variable is <?php echo $myVar; ?>

I include the .php file like:

include ("myFile.txt");
Thanasis
  • 329
  • 4
  • 8