Reputation: 3158
Let's consider that mytext.txt contains:
Hello my name is $name.
Then...
<?php
$name = "Johnny";
$output = file_get_contents("mytext.txt");
echo $output;
?>
I did this expecting $name to be replaced with the variable's value.
ps: I can't use include() because I need it to be stored in a variable.
Upvotes: 1
Views: 57
Reputation: 1310
use the pregmatch at all will be god way, here is the working example that i have tried before, just delete the $
and change to [name]
from your var
<?php
$name = "Johnny";
$output = file_get_contents("data.txt");
echo preg_replace('/\[name\]/',$name,$output);
?>
and the mytext.txt just put like this Hello my name is [name].
and the result will be Hello my name is Jhonny.
Upvotes: 1
Reputation: 3461
Yo have to use output buffering, like so:
<?php
$name = "Johnny";
ob_start();
include "mytext.txt";
$output = ob_get_contents();
ob_end_clean();
echo $output;
?>
And you file must be formatted as php:
Hello, my name is <?php echo $name ?>
In that way, your include you file. Your file is handeled as php and you can store outputted html as variable. More info here: http://php.net/manual/en/book.outcontrol.php
Upvotes: 3
Reputation: 11700
mytext.txt
<?php
$str = "Hello my name is $name.";
your.php
<?php
$name = "Johnny";
require_once 'mytext.txt';
echo $str;
Upvotes: 0