Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get include contents as a string? [duplicate]

Tags:

include

php

Possible Duplicate:
Execute a PHP file, and return the result as a string
PHP capture print/require output in variable

I am trying to get the contents of an include to a string. Is that possible?

For example, if I have a test.php file:

echo 'a is equal to '.$a;

I need a function, say include_to_string to include the test.php and return what would be output by in in a string.

Something like:

$a = 4;
$string = include_to_string(test.php); // $string = "a is equal to 4"
like image 967
ppp Avatar asked Apr 13 '12 15:04

ppp


2 Answers

ob_start();
include 'test.php';
$string = ob_get_clean();

I think is what you want. See output buffering.

like image 97
DaveRandom Avatar answered Oct 20 '22 01:10

DaveRandom


You can do this with output buffering:

function include2string($file) {
    ob_start();
    include($file);
    return ob_get_clean();
}

@DaveRandom points out (correctly) that the issue with wrapping this in a function is that your script ($file) will not have access to variable defined globally. That might not be an issue for many scripts included dynamically, but if it is an issue for you then this technique can be used (as others have shown) outside of a function wrapper.

** Importing variables One thing you can do is to add a set of data you would like to expose to your script as variables. Think of it like passing data to a template.

function include2string($file, array $vars = array()) {
    extract($vars);
    ob_start();
    include($file);
    return ob_get_clean();
}

You would call it this way:

include2string('foo.php', array('key' => 'value', 'varibleName' => $variableName));

and now $key and $variableName would be visible inside your foo.php file.

You could also provide a list of global variables to "import" for your script if that seems clearer to you.

function include2string($file, array $import = array()) {
    extract(array_intersect_key($GLOBALS, array_fill_keys($import, 1)));
    ob_start();
    include($file);
    return ob_get_clean();
}

And you would call it, providing a list of the globals you would like exposed to the script:

$foo='bar';
$boo='far';
include2string('foo.php', array('foo'));

foo.php should be able to see foo, but not boo.

like image 25
Prestaul Avatar answered Oct 20 '22 00:10

Prestaul