Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include PHP file as string

Tags:

include

php

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.

like image 801
SnackerSWE Avatar asked Sep 05 '25 11:09

SnackerSWE


2 Answers

file.php

ob_start();
include 'otherfile.php';
$string = ob_get_clean();
like image 178
MDEV Avatar answered Sep 08 '25 05:09

MDEV


$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

like image 31
Mark Baker Avatar answered Sep 08 '25 05:09

Mark Baker