Include file in variable

I try to have my code clear part of it in files (like similar libraries). But some of these files will 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:

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

So, I want to save what happens after php runs the variable for transmission later.

Using file_get_contents does not start php, it saves it as a string, so are there any options for this or am I out of luck?

UPDATE:

So how:

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

Or did you mean creating a function for each file?

+4
source share
2 answers

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

Using output buffering allows you to redirect standard output to memory, rather than sending it to the browser.


Here is a quick example:

 // Activate output buffering => all that 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 you will get:

 hello World !!! 
+10
source

What does your file/path/include.php ?

You will need to call file_get_contents via http to get its output, 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 using the function:

 <?php function CreateOutput() { // ... return $output; } ?> 

Then, turning it on, call the function to get the result.

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

Source: https://habr.com/ru/post/1343686/


All Articles