swamprunner7
swamprunner7

Reputation: 1319

How to pass the require_once output to a variable?

I want to call require_once("test.php") but not display result and save it into variable like this:

$test = require_once('test.php');

//some operations like $test = preg_replace(…);

echo $test;

Solution:

test.php

<?php
$var = '/img/hello.jpg';

$res = <<<test

<style type="text/css">
body{background:url($var)#fff !important;}
</style>

test;

return $res;
?>

main.php

<?php
$test = require_once('test.php');

echo $test;
?>

Upvotes: 29

Views: 28487

Answers (3)

Pekka
Pekka

Reputation: 449733

Is it possible?

Yes, but you need to do an explicit return in the required file:

//test.php

<? $result = "Hello, world!"; 
  return $result;
?>

//index.php

$test = require_once('test.php');  // Will contain "Hello, world!"

This is rarely useful - check Konrad's output buffer based answer, or adam's file_get_contents one - they are probably better suited to what you want.

Upvotes: 40

Adam Hopkinson
Adam Hopkinson

Reputation: 28793

file_get_contents will get the content of the file. If it's on the same server and referenced by path (rather than url), this will get the content of test.php. If it's remote or referenced by url, it will get the output of the script.

Upvotes: 4

Konrad Rudolph
Konrad Rudolph

Reputation: 545985

“The result” presumably is a string output?

In that case you can use ob_start to buffer said output:

ob_start();
require_once('test.php');
$test = ob_get_contents();

EDIT From the edited question it looks rather like you want to have a function inside the included file. In any case, this would probably be the (much!) cleaner solution:

<?php // test.php:

function some_function() {
    // Do something.
    return 'some result';
}

?>

<?php // Main file:

require_once('test.php');

$result = test_function(); // Calls the function defined in test.php.
…
?>

Upvotes: 36

Related Questions