SnackerSWE
SnackerSWE

Reputation: 659

Include PHP file as string

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.

Upvotes: 28

Views: 29352

Answers (5)

T.Kalweit
T.Kalweit

Reputation: 31

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.

Upvotes: 0

dqhendricks
dqhendricks

Reputation: 19251

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

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212522

$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

Upvotes: 15

maaudet
maaudet

Reputation: 2358

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

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

myfile.php:

<?php
return 'mystring';

Upvotes: 3

MDEV
MDEV

Reputation: 10838

file.php

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

Upvotes: 67

Related Questions