PHP: Can You Pass Include Through a Function? - php

Is it at all possible to include a file through a function? I don't mean returning the contents as a string. I'd like to create my own custom include method, but right now it doesn't seem possible.
For instance, PHP's include method outputs file contents. I'd like to output file contents, but run them through another function first.
For example:
function include_filter($file){
include($file);
}
include_filter($file);
This example does not use additional functionality, because my primary question here is how to include through a function at all. You can see the issue.
If I include through a function such as include_filter, the code will be included locally inside the function only, not at the line the function was called (line 4 in the example).

The include statement does not output the file contents. However, it does evaluate the file you're including, so if that file contains any echo statements then yes, those are executed the moment you include that file.
You can use an output buffer to catch that output and do something with it before re-echo'ing it:
included_file.php:
<?php
echo "This came from an included file.";
main_file.php:
<?php
function include_filter($path) {
ob_start();
include $path;
$output = ob_get_contents();
ob_end_clean();
echo str_replace("an included file", "a filter function", $output);
}
include_filter("included_file.php");
// will output "This came from a filter function."
Demo: https://3v4l.org/2XkL7

Related

Return html response from PHP page in to variable

I am trying to generate an email with some HTML that is created via another PHP file.
Email generating file is run by a cron running every hour.
Another file exists that generates the HTML required for the email.
The HTML generating file does not have a function that I can call, for instance:
$emailBody = generateHTML($id);
The HTML generating file was designed to be included on a page that you wished to display the HTML, for instance:
include "htmlGenerator.php";
My question is: How can I get what the htmlgenerator.php file returns in to a variable, ready to be pushed in to an email.
Apologies if this is not very clear, I will be happy to answer any questions.
Thanks in advance!
If I understood what you said, you can use output buffering,
so that you can get the output of htmlGenerator.php
For example:
ob_start();
// as an example
echo "Hello World";
// or in our case
include "htmlGenerator.php";
$result = ob_get_contents();
ob_end_clean();
You can also create a simple function like this:
function include_output($filename)
{
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
$mycontent = include_output("htmlGenerator.php");
Read the php documentation for further details.
Check out the built-in functions ob_start and ob_get_clean.
You can then do something like:
ob_start();
include( "file.php");
$var = ob_get_clean();

How to get multiple PHP files output into a single a file for further usage of those output?

I am trying to get the output of multiple PHP files into a single PHP file where I can save them into different variables for further usage.
For a single PHP file, I used include and it works well. But for multiple files I don't know what to do.
Do you have any experiences or advices on how to achieve this ?
I had three php files called a.php,b.php and c.php. Now in each file i am echoing an array as output. For first php file i done like below to save the output of that in fourth php file called d.php
ob_start();
include_once('a.php');
$output= ob_get_clean();
echo "<pre>";print_r($output);
Now what to do for getting second and third php files outputs.
I think this is what you want
<?php
$string1 = get_include_contents('somefile1.php');
$string2 = get_include_contents('somefile2.php');
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
?>

(PHP) How to pass the previous INCLUDE / REQUIRE calls into child files?

I'm creating my own Templating Script by using the ob_get_contents() as a core method. By using it, it can render out the other files, calling from the one single file.
Just like, lets assume we have 4 files:
index.php
header.html
footer.html
functions.php
index.php will call and render the contents of other files (2 html files here). By using the following codes:
//index.php
function render($file) {
if (file_exists($file)) {
ob_start();
include($file);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
}
echo render('header.html');
echo render('footer.html');
But (for example) when header.html contains a call include('functions.php'), the included file (functions.php) can't be used again in footer.html. I mean, i have to make a include again in footer.html. So here, the line include('functions.php') have to be containing in both of files.
How to include() a file without calling it again from child files?
When you use ob_start() (Output buffering), you end up only with the output of the file, meaning file executed the output is returned by ob_get_content(). As only output is returned that other file is unaware of the includes.
So the answer is: you can't do it with output buffering. Or include your files before ob_start with include_once.
That could work like something like this:
//index.php
function render($file) {
if(!isset($GLOBALS['included'])) {
$GLOBALS['included'] = array();
}
if (!in_array($file, $GLOBALS['included']) && file_exists($file)) {
ob_start();
include($file);
$content = ob_get_contents();
ob_end_clean();
$GLOBALS['included'][] = $file;
return $content;
}
}
echo render('header.html');
echo render('footer.html');
Alternatively you could use include_once (include_once $file;)and PHP will do it for you.
Though I suggest you just make sure the file loading structure is in such shape that these events never happen.

Setting $variable's content using include()

I'm trying to send out a voucher, via the PHP's email() function, where I reference an external .php file using include() as the message contents. Heres the code:
$message = '<?php include ("/fullpath/inc/voucher.php"); ?>';
This isn't working because I'm declaring it as a text string, but if I don't it will just print out the contents and not put it as the content of the variable. Any ideas?
You can use the ob_buffer for that, try this:
<?php
ob_start(); // start buffer
include("file.php"); // read in buffer
$var=ob_get_contents(); // get buffer content
ob_end_clean(); // delete buffer content
echo $var; // use $var
?>
Example from http://www.webmaster-eye.de/include-in-Variable-umleiten.210.artikel.html (German)
In this post two solutions depending on the circumstances will be described..
voucher.php is returning a value
If voucher.php has a return statement in it you can safely use include to get a hold of this returned value.
See the below example:
voucher.php
<?php
$contents = "hello world!";
...
return $contents;
?>
...
$message = include ("/fullpath/inc/voucher.php");
voucher.php is printing data that I'd like to store in a variable
If voucher.php is printing data that you'd like to store in a variable you can use php's output buffering functions to store away the printed data and then assign it to $message.
ob_start ();
include ("/fullpath/inc/voucher.php");
$message = ob_get_contents ();
ob_end ();
ob_start();
include ("/fullpath/inc/voucher.php");
$message = ob_get_clean();
However output buffering in most cases is considered as bad practice and not recommended to use
Like in your case you better have a function declared in voucher.php that returns the message as a string. So all the code could be as simple as: $message = get_voucher();
I've encountered the same ploblem, here is the functions that resolves the problem for me. It uses the Tobiask answer
function call_plugin($target_) { // $target_ is the path to the .PHP file
ob_start(); // start buffer
include($target_); // read in buffer
$get_content = ob_get_contents(); // get buffer content
ob_end_clean();
return $get_content;
}
You want to use the readfile() function instead of include.
See: http://en.php.net/manual/en/function.readfile.php
If you want to get the =results= of PHP parsing the voucher.php one way is to make sure that you put voucher.php on a reachable URL, and then call it like:
$message = file_get_contents("http://host.domain.com/blabla/voucher.php");
This would insert the contents/output of the parsed voucher.php into the variable $message.
If you can't reach the voucher.php publically you have to rewrite it to output the string in the end with the return() function, or write a function in voucher.php that outputs the string you want when called after which you include() it and call the function from within this master PHP script.
$message = include '/fullpath/inc/voucher.php';
and withing /fullpath/inc/voucher.php
// create $string;
return $string;
$message=file_get_contents("/fullpath/inc/voucher.php");

Set included PHP and HTML content to a variable

I am working on a small MVC "framework", which will simply provide a more organized workspace for me, as I've found I love CakePHP but only for it's organization. Now, I'm trying to replicate the layouts (which contain <?php echo $title_for_layout; ?> and <?php echo $content_for_layout; ?>,) and I'm curious how I would be able to load a mixed PHP and HTML file... save what would normally be outputted to the browser to a variable... set the variables mentioned inside the variable, and then output the layout variable and have PHP use the variables inside it to setup the layout exactly how I want it.
Any ideas?
Capture the buffer output to a string with the output buffer control functions.
$string = getIncludeContents('template.php');
function getIncludeContents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
Example taken from.

Categories