I’m got a function thats using file_get_content to grab a piece of html with some vars in it. the idea is then to update the vars with some stuff this function fetch from the db and return it. However, on the output the variable just reads $myNameVar instead of My Name. Let me paste my code.
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;
}
}
}
And the content of item.php:
<p>My name is <span style="color: #000;">$myNameVar</span></p>
Here’s the call to the function:
<?php echo $queryDb->query("SELECT * FROM sometable","item");?>
And here is the output:
My Name is $myNameVar
When it should be:
My Name is My Name
I’ve tried to replace the variable in the item.php file to %% and run a foreach to update the variables like so (different function):
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;
}
}
}
This works partially, unfortunately this just return the first item for each row. So if in the first row $myNameVar = Joe and the second row $myNameVar = James both paragraphs would list the name as Joe like this: Joe Joe, not Joe James as it should.
Any help would be greatly appreciated 🙂
That’s because
file_get_contents()passes in the contents of the file as a string, not as executable PHP code.Use
include()instead.