Pass value to variable in PHP fopen

0

Opa,

I'm reading and viewing the contents of a .php file:

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

echo $conteudo;

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

echo is returning this to me:

<?php echo $variavel;?>

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

    
asked by anonymous 14.11.2015 / 03:06

1 answer

1

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

  

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

If you want to run model.php , I recommend that you use include because then it will execute the script called, but I'm not sure what you want, so follow the answer ...

As I said fopen does not execute php scripts, it reads only, the only way I can see 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+ opens 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 within '...' (apostrophes) does not execute the variables.

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

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

echo $conteudo;

If you have more variables you can use strtr , like this:

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

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

$conteudo = strtr($conteudo, $trans);
    
14.11.2015 / 03:25