1

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.

1
  • very nice question. that kind of problem has crossed my mind for another project. you've got my vote for that and i think answers are clearly enough. may be you should accept one of them. Commented Jan 13, 2012 at 5:26

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Just tried it. It displayed the same thing: Hello my name is $name.
If you need to keep the file format than you have to write somekindof template engine, what will preg_replace() or str_replace() to remplate variables. Or use some templating engine: webresourcesdepot.com/19-promising-php-template-engines
1

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.

4 Comments

The it will output Hemmo my Jonnhy is Jonhhy :)
It's not a bad idea. But my post just showed an example. In my web app there's actually a text file with LOTS of variables, so I would need a preg_replace for every variable which doesnt seem like a very good approach.
just use an array to replace them all, this quit easy isn't ? using pattern as an array and the replacement as an array is the good way, you don' have to use preg_replace() for every variable, just use an array for both pattern and replacement
I would do it using preg_replace_callback. First matching all variable patterns from file and then replacinh them usin dynamic variables.
0

mytext.txt

<?php
$str = "Hello my name is $name.";

your.php

<?php
$name = "Johnny";
require_once 'mytext.txt';
echo $str;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.