将PHP文件包含为字符串

Sna*_*SWE 21 php include

有可能做出这样的事吗?

// 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>
Run Code Online (Sandbox Code Playgroud)

得到这个输出?

<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<p>Lorem ipsum something</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我知道代码不起作用,但我希望你理解我的意思.

Smo*_*PHP 53

file.php

ob_start();
include 'otherfile.php';
$string = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案比Mark Ba​​kers更好-如果您想在otherfile.php中执行PHP代码 (2认同)

Mar*_*ker 11

$string = file_get_contents('otherfile.php',TRUE);
echo $string
Run Code Online (Sandbox Code Playgroud)

对file_get_contents()使用TRUE参数意味着它将使用包含路径进行搜索,就像普通包含或要求一样

  • 如果此文件中有PHP,则不会被解释,您需要使用eval或类似的东西. (2认同)
  • Manhim,我知道它需要变形(或者如果被显示回声那么漂亮)....那是我对OP想要的东西的解读. (2认同)