Include a file into a variable - php

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?

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

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());

Related

PHP replace {replace_me} with <?php include ?> in output buffer

I have a file like this
**buffer.php**
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
ob_end_flush();
Everything inside the buffer is dynamically made with data from the database.
And inserting php into the database is not an option.
The issue is, I got my output buffer and i want to replace '{replace}' with a working php include, which includes a file that also has some html/php.
So my actual question is: How do i replace a string with working php-code in a output-buffer?
I hope you can help, have used way to much time on this.
Best regards - user2453885
EDIT - 25/11/14
I know wordpress or joomla is using some similar functions, you can write {rate} in your post, and it replaces it with a rating system(some rate-plugin). This is the secret knowledge I desire.
You can use preg_replace_callback and let the callback include the file you want to include and return the output. Or you could replace the placeholders with textual includes, save that as a file and include that file (sort of compile the thing)
For simple text you could do explode (though it's probably not the most efficient for large blocks of text):
function StringSwap($text ="", $rootdir ="", $begin = "{", $end = "}") {
// Explode beginning
$go = explode($begin,$text);
// Loop through the array
if(is_array($go)) {
foreach($go as $value) {
// Split ends if available
$value = explode($end,$value);
// If there is an end, key 0 should be the replacement
if(count($value) > 1) {
// Check if the file exists based on your root
if(is_file($rootdir . $value[0])) {
// If it is a real file, mark it and remove it
$new[]['file'] = $rootdir . $value[0];
unset($value[0]);
}
// All others set as text
$new[]['txt'] = implode($value);
}
else
// If not an array, not a file, just assign as text
$new[]['txt'] = $value;
}
}
// Loop through new array and handle each block as text or include
foreach($new as $block) {
if(isset($block['txt'])) {
echo (is_array($block['txt']))? implode(" ",$block['txt']): $block['txt']." ";
}
elseif(isset($block['file'])) {
include_once($block['file']);
}
}
}
// To use, drop your text in here as a string
// You need to set a root directory so it can map properly
StringSwap($text);
I might be misunderstanding something here, but something simple like this might work?
<?php
# Main page (retrieved from the database or wherever into a variable - output buffer example shown)
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
$main = ob_get_clean();
# Replacement
ob_start();
include 'whatever.php';
$replacement = ob_get_clean();
echo str_replace('{replace_me_with_working_php_include}', $replacement, $main);
You can also use a return statement from within an include file if you wish to remove the output buffer from that task too.
Good luck!
Ty all for some lovely input.
I will try and anwser my own question as clear as I can.
problem: I first thought that I wanted to implement a php-function or include inside a buffer. This however is not what I wanted, and is not intended.
Solution: Callback function with my desired content. By using the function preg_replace_callback(), I could find the text I wanted to replace in my buffer and then replace it with whatever the callback(function) would return.
The callback then included the necessary files/.classes and used the functions with written content in it.
Tell me if you did not understand, or want to elaborate/tell more about my solution.

Output buffering, hierarchical?

Output buffering in PHP is fun. It simplifies many things. I use ob_start() at the top of the script and ob_get_clean() (or any other function) at the bottom.
Between those two calls is it possible to call those functions again, without interfering the parent calls.
Is this type of code valid ? (it works fine, but...) Is this a good habit ?
<?php
ob_start(); //NOTICE !!!
echo '<p>echos of the top of the script</p>';
echo GetSomeOtherData(true);
echo '<p>echos after GetSomeOtherData()</p>';
$data = ob_get_clean(); //NOTICE !!!
echo $data;
//just a function to return something, with the help of output buffering
function GetSomeOtherData($toReturn)
{
ob_start(); //NOTICE !!!
echo '<p>This has been rendered inside a function</p>';
$function_data = ob_get_clean(); //NOTICE !!!
if($toReturn===true)
{
return $function_data;
}
else
{
//may be an error | return something else
return '<p>An Error</p>';
}
}
?>
From the ob_start() manual:
Output buffers are stackable, that is, you may call ob_start() while
another ob_start() is active. Just make sure that you call
ob_end_flush() the appropriate number of times. If multiple output
callback functions are active, output is being filtered sequentially
through each of them in nesting order.
So it is perfectly valid to assume that an ob_end/get will end/return the matching ob_start e.g.:
ob_start();
echo "<div class=outer>";
ob_start();
echo "<div class=inner></div>";
$inner = ob_get_clean(); // <div class=inner></div>
echo "</div>";
$outer = ob_get_clean(); // <div class=outer></div>
In all honesty, I don't see any problem with that. Every call to ob_start() is matched by an ob_get_clean() call, so the use of such functions is completely transparent to the "parent" ob_start(). It would be a horrible habit if pairs (of calls to ob_start() and ob_get_clean()) didn't match -- but as long as they do, it shouldn't (and won't) cause you any trouble.

how to turn the output of a require statement into a string in php

im working with a large team, and im making functions that return html code, and im echoing the result of those functions to get the final page. The thing is, i need some scrap of code developed by other member of the team, and i need it to be a string, but the code is available as a php file which im supposed to include or require inside my page.
Since im not writing an ht;ml page, but a function that generate that code, i need to turn the resulting html of the require statement into a string to concatenate it to the code generated by my function.
Is there any way to evaluate the require and concatenate its result to my strings?
Ive tried the function eval(), but didnt work, and read some thing about get_the_content(), but it isnt working either. I dont know if i need to import something, i think it have something to do with wordpress, and im using raw php.
thanks for all your help!!! =)
Try the ob_...() family of functions. For example:
<?php
function f(){
echo 'foo';
}
//start buffering output. now output will be sent to an internal buffer instead of to the browser.
ob_start();
//call a function that echos some stuff
f();
//save the current buffer contents to a variable
$foo = ob_get_clean();
echo 'bar';
echo $foo;
//result: barfoo
?>
If you want to put the echo'd result of an include into a variable, you could do something like this:
//untested
function get_include($file){
ob_start();
include($file);
return ob_get_clean();
}
or if you want to put the echo'd result of a function call into a variable, you could do something like this:
//untested
//signature: get_from_function(callback $function, [mixed $param1, [mixed $param2, ... ]])
function get_from_function($function){
$args = func_get_args();
shift($args);
ob_start();
call_user_func_array($function,$args);
return ob_get_clean();
}
Depending on how the other file works...
If the other file can be changed to return a value, then you should use:
$content = require 'otherfile';
If the other file simply uses echo or some other way to print directly, use:
ob_start();
require 'otherfile';
$content = ob_get_clean();
You can receive string with include or require but you have to update those files before including to add return statement.
the file to be included should return result like this
<?php
$var = 'PHP';
return $var;
?>
and you can receive the $var data by including that file
$foo = include 'file.php';
echo $foo; // will print PHP
Documentation section

PHP: Can I suppress output of a function?

So I know you can use output buffer. The problem right now is, I am using a function in a Wordpress plugin and it is automatically and it automatically outputs the return. However, I want to check the return to see if it is false or returning my data.
I have tried:
if( function_name() ) {
}
$name = function_name();
I can still see the output in those situations, which I why I wanted to suppress it and do some checks first. I don't want to edit the core function of the plugin, but I will as a last resort. Is there a better work around?
Yes. It can be done like this:
ob_start();
if (function_name()) { }
else {}
// then you can do one of the following
ob_end_clean(); // in case you want to suppress function_name output
ob_flush(); // in case you don't want to suppress function_name output
Have a look here for more information about output control functions.
Also, instead of using ob_flush and ob_end_clean you could use ob_get_clean.
First, capture the output and return value of the function.
ob_start();
$name = function_name();
$output = ob_get_clean();
Next, decide whether or not you want to output it.
if ($name !== false) {
echo $output;
}
You weren't clear what you wanted to do with the return value if it wasn't false or if it was actually the output of the function that you wanted to send to the page.

php print whole page

Quite simple question i belive. How to print the whole page into variable and then use where i need.
For instance if the code is:
<?php
$arr = array('hello','mate','world');
foreach ($arr as $a) {print "<p>".$a."</p>"; }
?>
Now if we go to that page, we can see an array output, but i would prefer to print the whole page into variable and then generate static page for instance out of that.
Maybe file_get_content or <<<EOT, but the page will get more complicated later so not sure what is the best option.
Not sure about your exact needs but:
ob_start();
require('/path/to/templates/foo.php');
$template = ob_get_contents();
ob_get_clean();
ob_start();
// your code
$var = ob_get_clean();
print $var;
Why don't you use smarty ,
put all HTML in a template , and insert PHP code or variables into it . in the end , using $x=$smarty->fetch('template_name'); you put all the page in the $x variable ...

Categories