如何在php数组中使用变量从文件中读取[关闭]
问题描述:
I am trying to figure out how to use a variable in an array that has been read from a file. This is what I have thus far and it is returning the variable name instead of the value. The example intentionally does not have a space between $var.doe and saint.$var AND places the $var in front of "doe" and behind "saint" because that is the actual data we are dealing with. Thank you for your help.
read.txt
$var.doe
saint.$var
php file
<?
$var = "john";
$aArray = file('read.txt');
echo $aArray[0];
echo '<br>';
echo $aArray[1];
?>
答
You need to substitute the variables:
php > $s = '
$var.doe
saint.$var
';
php > echo $s;
$var.doe
saint.$var
php > $var = 'jone';
php > echo str_replace('$var', $var, $s);
john.doe
saint.john
答
You must do something like this : read.txt
doe
saint
php file
<?php
$var = "john";
$aArray = file('read.txt');
echo $var." ".$aArray[0];
echo $aArray[1]." ".$var;
?>
all the variable must be on the php file and all the string must be on the txt file.