4

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?

jefffan24
  • 1,326
  • 3
  • 20
  • 35

2 Answers2

10

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 !!!
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • So if I did an include instead of an echo and then did the ob_get_clean on a variable it should work? – jefffan24 Mar 14 '11 at 20:59
  • If you included file echoes something, it'll get buffered -- and you'll be able to get it to a variable *(hoping I understood the question right)* – Pascal MARTIN Mar 14 '11 at 21:02
0

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());
Czechnology
  • 14,832
  • 10
  • 62
  • 88
  • @jefffan24, No, that's not what I meant, that would do exactly the same as before. I meant performing the actions that are in your file _$filename_ directly in the function and saving it in a variable $output, then sending it back. Either work with the variable all the time or use [output buffering](http://php.net/manual/en/book.outcontrol.php). It's hard to tell when we don't know your file and what's in it - and what exactly are you performing with php there. – Czechnology Mar 14 '11 at 21:00