php - file_get_content 和变量问题

标签 php mysql function variables foreach

我有一个函数,它使用 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/

相关文章:

php - MySQL Numrows 期望参数

mysql - 两个sql查询之间的区别(使用join和不使用join)

function - 带有 =(等号)的 Scala 方法

javascript - 检测是否有任何 JavaScript 函数正在运行

javascript - angularjs 中的 $watch 方法真正返回什么以及它是如何工作的?

php - 一个php文件怎么能等别人呢?

php - 在 PHP 中捕获重复字母 - 正则表达式

javascript - PHP防止同一页面上多个表单重新提交

mysql - sphinx 搜索 max_matches 无法使用 sphinx.yml 文件工作

php - 无法使用 PHP 和 Mysql 退出循环