27

is it possible to make something like this?

// file.php
$string = require('otherfile.php');
echo $string;

// otherfile.php
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<?php require 'body.php';?>
</body>
</html>

// body.php
<p>Lorem ipsum something</p>

And get this output?

<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<p>Lorem ipsum something</p>
</body>
</html>

I know that code won't work, but I hope you understand what I mean.

SnackerSWE
  • 649
  • 1
  • 10
  • 19

5 Answers5

65

file.php

ob_start();
include 'otherfile.php';
$string = ob_get_clean();
MDEV
  • 10,730
  • 2
  • 33
  • 49
14
$string = file_get_contents('otherfile.php',TRUE);
echo $string

Use of the TRUE argument for file_get_contents() means it will search using the include path, like a normal include or require

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 2
    If there is PHP in this file it's not going to be interpreted, you would need to use eval or something similar. – maaudet Jan 06 '12 at 01:29
  • 2
    Manhim, I'm aware it would need evalling (or prettyfying if being echoed for display).... that was my reading of what OP wanted. – Mark Baker Jan 06 '12 at 07:30
3

Another cool thing to know, but SmokeyPHP's answer might be better:

<?php
$var = require 'myfile.php';

myfile.php:

<?php
return 'mystring';
maaudet
  • 2,338
  • 4
  • 20
  • 28
1

Yes, you can use a return statement in a file, and requires and includes will return the returned value, but you would have to modify the file to say something more like

<?php
    return '<p>Lorem ipsum something</p>';
?>

check example #5 under include documentation http://www.php.net/manual/en/function.include.php

dqhendricks
  • 19,030
  • 11
  • 50
  • 83
0

I need a solution for Joomla and dompdf and I found this solution

ob_start();
require_once JPATH_COMPONENT . DIRECTORY_SEPARATOR . 'file.php';
$html = ob_get_clean();

only with require_once can use all functions from Joomla at the loaded script. The file.php is a .html file renamed to .php and where added php code.

T.Kalweit
  • 31
  • 3