Get content of another PHP file and use variables for the current PHP file

I want to use a variable inside HTML-String of another PHP file template.php

in my PHP file constructor.php

.

I searched on Stackoverflow for a workaround to include the content of another PHP file. I've included the following code in constructor.php

because it's known to be more secure, instead of using file_get_contents();

Source :

function requireToVar($file){
    ob_start();
    require($file);
    return ob_get_clean();
}

      

The rest constructor.php

looks like this:

...
    $sqli = mysqli_query($mysqli, "SELECT ...");
    if(mysqli_num_rows($sqli) > 0){
        $ii = 0;
        while ($row = $sqli->fetch_assoc()) {
            $ii++;
            if($row['dummy']=="Example"){
                $content.=requireToVar('template.php');
...

      

template.php

as follows:

<?php echo "
   <div class='image-wrapper' id='dt-".$row['id']."' style='display: none;'>
   ...
   </div>
"; ?>

      

constructor.php

does not recognize var $row['id']

within a string template.php

as its own variable, and neither does it. The variable definitely works for other code in constructor.php

.

If I copy and paste the code template.php

in constructor.php

after $content.=

, it works like a charm. But I want to restructure mine constructor.php

because it gets larger and thus easier to customize.

I do not know how best to describe this problem, but I hope this name matches my problem.

+3


source to share


3 answers


Update your function

function requireToVar($file,$row_id){
    ob_start();
    require($file);
    return ob_get_clean();
}

      

so you can call it that



while ($row = $sqli->fetch_assoc()) {
        $ii++;
        if($row['dummy']=="Example"){
            $content.=requireToVar('template.php',$row['id']);

      

and display it in template.php file like

<div class="image-wrapper" id="dt-<?php echo $row_id; ?>" style="display: none;"></div>

      

+1




Use MVC model features and renderers. For example: index.php

<!DOCTYPE HTML>
<html>
    <head>
        <title><?=$title; ?></title>
    </head>
    <body>
        <h3><?=$text; ?></h3>
    </body>
</html>

      

Than I will have a PHP array containing these variables:



$array = array("title"=>"Mypage", "text"=>"Mytext");

      

Now we will use both in renderer function

function renderer($path, $array)
{
    extract($array); // extract function turn keys into variables
    include_once("$path.php");
} 
renderer("index", $array);

      

0




Your approach is rather strange, but anyway; you can access $ row from $ GLOBALS array.

Write your template as:

<?php echo "
   <div class='image-wrapper' id='dt-".$GLOBALS['row']['id']."' style='display: none;'>
   ...
   </div>
"; 
?>

      

0


source







All Articles