简体   繁体   中英

(PHP) Getting content from a file that uses variables

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.

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

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.

mytext.txt

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

your.php

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM