Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the require_once output to a variable?

Tags:

file

php

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;
?>
like image 629
swamprunner7 Avatar asked May 13 '10 21:05

swamprunner7


3 Answers

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.

like image 71
Pekka Avatar answered Nov 15 '22 07:11

Pekka


“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.
…
?>
like image 41
Konrad Rudolph Avatar answered Nov 15 '22 06:11

Konrad Rudolph


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.

like image 37
Adam Hopkinson Avatar answered Nov 15 '22 06:11

Adam Hopkinson