Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include a file into a variable

I am trying to keep my code clean break up some of it into files (kind of like libraries). But some of those files are going to need to run PHP.

So what I want to do is something like:

$include = include("file/path/include.php");
$array[] = array(key => $include);

include("template.php");

Than in template.php I would have:

foreach($array as $a){
    echo $a['key'];
}

So I want to store what happens after the php runs in a variable to pass on later.

Using file_get_contents doesn't run the php it stores it as a string so are there any options for this or am I out of luck?

UPDATE:

So like:

function CreateOutput($filename) {
  if(is_file($filename)){
      file_get_contents($filename);
  }
  return $output;
}

Or did you mean create a function for each file?

like image 843
jefffan24 Avatar asked Dec 27 '22 23:12

jefffan24


1 Answers

It seems you need to use Output Buffering Control -- see especially the ob_start() and ob_get_clean() functions.

Using output buffering will allow you to redirect standard output to memory, instead of sending it to the browser.


Here's a quick example :

// Activate output buffering => all that's echoed after goes to memory
ob_start();

// do some echoing -- that will go to the buffer
echo "hello %MARKER% !!!";

// get what was echoed to memory, and disables output buffering
$str = ob_get_clean();

// $str now contains what whas previously echoed
// you can work on $str

$new_str = str_replace('%MARKER%', 'World', $str);

// echo to the standard output (browser)
echo $new_str;

And the output you'll get is :

hello World !!!
like image 82
Pascal MARTIN Avatar answered Jan 11 '23 22:01

Pascal MARTIN