IMB
IMB

Reputation: 15919

PHP: Pass variables to file_get_contents()

Is there a way to make this possible?

// file.php
echo $foo;

then in

// test.php
$foo = 'bar';
echo file_get_contents('file.php');

The output of test.php should be "bar".

Upvotes: 1

Views: 1490

Answers (3)

Jared
Jared

Reputation: 301

I use:

$foo = 'bar';
require_once('./file.php');

And in file.php it's just:

echo $foo;

Upvotes: 1

Simon Forsberg
Simon Forsberg

Reputation: 13351

I would do it like this:

// file.php
function outputFoo($foo) {
  echo $foo;
}


// test.php
$foo = 'bar';
include 'file.php';
outputFoo($foo);

But really, all that is actually needed in your case is:

// file.php
echo $foo;

// test.php
$foo = 'bar';
include 'file.php';

As file.php will have access to your $foo-variable as well. (This only works when file.php and test.php is within the same domain).

Upvotes: 1

deceze
deceze

Reputation: 522597

ob_start();
include 'file.php';
echo ob_get_clean();

But really, this seems like a rather nonsensical thing to do. If you just want file.php evaluated and have it output its contents, simply include the file.

Upvotes: 0

Related Questions