0

I have a php page that is reading from a file:

$name = "World";
$file = file_get_contents('html.txt', true);
$file = file_get_contents('html.txt', FILE_USE_INCLUDE_PATH);

echo $file;

In the html.txt I have the following:

Hello $name!

When I go to the site, I get "Hello $name!" and not Hello World!

Is there a way to get var's in the txt file to output their value and not their name?

Thanks, Brian

Brian V.
  • 37
  • 1
  • 8

3 Answers3

2

The second param of file_get_contents has nothing to do with how to interpret the file - it's about which pathes to check when looking for that file.

The result, however, will always be a complete string, and you can only "reinterpolate" it with evial.

What might be a better idea is using the combination of include and output control functions:

Main file:

<?php

$name = "World";
ob_start();
include('html.tpl');
$file = ob_get_clean();
echo $file;

html.tpl:

Hello <?= $name ?>

Note that php tags (<?= ... ?>) in the text ('.tpl') file - without it $name will not be parsed as a variable name.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
1

One possible approach with predefined values (instead of all variables in scope):

    $name = "World";
    $name2 = "John";

    $template = file_get_contents ('html_templates/template.html');

    $replace_array = array(
        ':name' => $name,
        ':name2' => $name2,
        ...
    );

    $final_html = strtr($template, $replace_array);

And in the template.html you would have something like this:

    <div>Hello :name!</div>
    <div>And also hi to you, :name2!</div>
Bojan Hrnkas
  • 1,587
  • 16
  • 22
0

To specifically answer your question, you'll need to use the 'eval' function in php. http://php.net/manual/en/function.eval.php

But from a development perspective, I would consider if there was a better way to do that, either by storing $name somewhere more accessible or by re-evaluating your process. Using things like the eval function can introduce some serious security risks.