Search code examples
phpfilereturnfile-get-contents

How to execute and get content of a .php file in a variable?


I want to get contents of a .php file in a variable on other page.

I have two files, myfile1.php and myfile2.php.

myfile2.php

<?PHP
    $myvar="prashant"; // 
    echo $myvar;
?>

Now I want to get the value echoed by the myfile2.php in an variable in myfile1.php, I have tried the follwing way, but its taking all the contents including php tag () also.

<?PHP
    $root_var .= file_get_contents($_SERVER['DOCUMENT_ROOT']."/myfile2.php", true);
?>

Please tell me how I can get contents returned by one PHP file into a variable defined in another PHP file.

Thanks


Solution

  • You can use the include directive to do this.

    File 2:

    <?php
        $myvar="prashant";
    ?>
    

    File 1:

    <?php 
    
    include('myfile2.php');
    echo $myvar;
    
    ?>