将 PHP 文件包含为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8751182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:25:10  来源:igfitidea点击:

Include PHP file as string

phpinclude

提问by SnackerSWE

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.

我知道代码行不通,但我希望你明白我的意思。

回答by SmokeyPHP

file.php

文件.php

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

回答by Mark Baker

$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

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

回答by maaudet

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

另一件很酷的事情要知道,但 SmokeyPHP 的答案可能更好:

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

myfile.php:

我的文件.php:

<?php
return 'mystring';

回答by dqhendricks

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

是的,您可以在文件中使用 return 语句,并且 requires 和 includes 将返回返回的值,但是您必须修改文件以说出更像

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

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

检查包含文档http://www.php.net/manual/en/function.include.php下的示例 #5

回答by T.Kalweit

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

我需要 Joomla 和 dompdf 的解决方案,我找到了这个解决方案

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.

只有 require_once 才能在加载的脚本中使用 Joomla 的所有功能。file.php 是一个 .html 文件,重命名为 .php 并在其中添加了 php 代码。

回答by anonymous coward

<?php require "otherfile.php";