将 PHP 文件作为字符串包含在内

2022-08-30 16:18:38

有可能做这样的东西吗?

// 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>

并得到这个输出?

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

我知道代码不起作用,但我希望你明白我的意思。


答案 1

文件.php

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

答案 2
$string = file_get_contents('otherfile.php',TRUE);
echo $string

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


推荐