我有一个函数,它使用 file_get_content 来获取一段包含一些变量的 html。然后,我们的想法是用该函数从数据库获取的一些内容来更新变量并返回它。但是,在输出中,变量仅读取 $myNameVar 而不是 My Name。让我粘贴我的代码。
function query($query,$item)
{
$this->item = file_get_contents("/pages/items/".$item.".php");
$this->queryResult = mysql_query($query);
if(mysql_num_rows($this->queryResult))
{
while($row = mysql_fetch_assoc($this->queryResult))
{
extract($row);
// $myNameVar = My Name;
// in the finished code there will be a bunch (15 or more) vars
// that needs to be updated in the Item file so the vars
// must be updated automatically
return $this->item;
}
}
}
以及item.php的内容:
<p>My name is <span style="color: #000;">$myNameVar</span></p>
这是对该函数的调用:
<?php echo $queryDb->query("SELECT * FROM sometable","item");?>
这是输出:
My Name is $myNameVar
什么时候应该是:
My Name is My Name
我尝试将 item.php 文件中的变量替换为 %% 并运行 foreach 来更新变量,如下所示(不同的函数):
function query($query,$item)
{
$this->item = file_get_contents("/pages/items/".$item.".php");
$this->queryResult = mysql_query($query);
if(mysql_num_rows($this->queryResult))
{
while($row = mysql_fetch_assoc($this->queryResult))
{
foreach ($row as $key => $value)
{
$this->item = str_replace("%".$key."%",$value,$this->item);
}
return $this->item;
}
}
}
这部分有效,不幸的是这只是返回每行的第一项。因此,如果在第一行 $myNameVar = Joe 和第二行 $myNameVar = James 中,两个段落都会将名字列为 Joe,如下所示:Joe Joe,而不是应有的 Joe James。
任何帮助将不胜感激:)
最佳答案
这是因为 file_get_contents()
将文件内容作为字符串传递,而不是作为可执行 PHP 代码。
改用include()
。
关于php - file_get_content 和变量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4129384/