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
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.
The file_get_contents() function reads entire file into a string. The file() function reads the entire file in a array, whereas file_get_contents() function reads the entire file into a string.
You have to differentiate two things:
echo
, print
,...) of the included file and use the output in a variable (string)?Local variables in your included files will always be moved to the current scope of your host script - this should be noted. You can combine all of these features into one:
include.php
$hello = "Hello"; echo "Hello World"; return "World";
host.php
ob_start(); $return = include 'include.php'; // (string)"World" $output = ob_get_clean(); // (string)"Hello World" // $hello has been moved to the current scope echo $hello . ' ' . $return; // echos "Hello World"
The return
-feature comes in handy especially when using configuration files.
config.php
return array( 'host' => 'localhost', .... );
app.php
$config = include 'config.php'; // $config is an array
EDIT
To answer your question about the performance penalty when using the output buffers, I just did some quick testing. 1,000,000 iterations of ob_start()
and the corresponding $o = ob_get_clean()
take about 7.5 seconds on my Windows machine (arguably not the best environment for PHP). I'd say that the performance impact should be considered quite small...
If you only wanted the content echo()
'ed by the included page, you could consider using output buffering:
ob_start(); include 'myfile2.php'; $echoed_content = ob_get_clean(); // gets content, discards buffer
See http://php.net/ob_start
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With