Pass value to variable in fopen PHP

Asked

Viewed 499 times

0

Opa,

I’m reading and displaying the contents of a. php file:

$arq="modelo.php";
$abre=fopen($arq,"r+");
$conteudo=fread($abre,filesize($arq));
fclose($abre);

echo $conteudo;

I normally echo html, but I need to pass values to the variables of the.php model file. When echoing the contents of the.php template file, what is displayed are the tags and not the content, ie:

echo is returning this to me:

<?php echo $variavel;?>

I will need this for automatic simple page generation, the complete layout is in the.php template, and the main page values are generated dynamically.

  • Generate pages? This makes no sense, maybe the best would be to use include, as I said fopen does not run scripts.

1 answer

1


This phrase of yours seems confusing, because you need something seemingly simple, but you want to do it the "hard way".

I will need this for automatic simple page generation, the complete layout is in the.php template, and the main page values are generated dynamically.

If you want to execute model.php, recommend using include because then it will run the script called, but not quite sure what you want, so follow the answer...

Like I said the fopen does not execute php scripts, it reads only, the only way I see to achieve is to use str_replace or strtr, for example:

$arq="modelo.php";
$abre=fopen($arq, "r+");
$conteudo = fread($abre, filesize($arq));
$conteudo = str_replace('$variavel', $variavel, $conteudo);
fclose($abre);

echo $conteudo;

Note that r+ open the file to edit (put the pointer at the end) and read, in your case it seems that you just want to read, then you can use file_get_contents, for example:

$arq = 'modelo.php';
$conteudo = file_get_contents($arq);
$conteudo = str_replace('$variavel', $variavel, $conteudo);

echo $conteudo;

Note that writing $var inside '...' (quote) does not execute variables.

A detail, if there is any variable type $variavel2 this may be a problem, so maybe it is better to use regex, example:

$conteudo = preg_replace('#\$(variavel)([^a-z0-9]+)#',
                          '$' . $variavel . '$2', $conteudo);

echo $conteudo;

If you have more variables you can use strtr, thus:

$arq = 'modelo.php';
$conteudo = file_get_contents($arq);

$trans = array(
            '$varA' => $varA,
            '$varB' => $varB,
            '$varC' => $varC,
            '$varD' => $varD,
            '$varE' => $varE
         );

$conteudo = strtr($conteudo, $trans);
  • Show, worked beauty with str_replace and file_get_contents, but, I have on average some 8 variables to pass, it is possible to do this with preg_replace?

  • @sNniffer I do not understand well this your need, posted an example with strtr to use several variables, but I ask you to explain in your question the reason for this need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.