jefffan24
jefffan24

Reputation: 1326

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?

Upvotes: 4

Views: 4213

Answers (2)

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

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 !!!

Upvotes: 10

Czechnology
Czechnology

Reputation: 15012

How does your file/path/include.php look like?

You would have to call file_get_contents over http to get the output of it, e.g.

$str = file_get_contents('http://server.tld/file/path/include.php');

It would be better to modify your file to output some text via a function:

<?php

function CreateOutput() {
  // ...
  return $output;
}

?>

Than after including it, call the function to get the output.

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

Upvotes: 0

Related Questions