包含 php 文件,但以字符串形式返回输出而不是打印

3 php include

我想包含一个文件,但我不想打印输出,而是想将其作为字符串获取。

例如,我想包含一个文件:

<?php echo "Hello"; ?> world!
Run Code Online (Sandbox Code Playgroud)

但我不想Hello world!在包含文件时进行打印,而是想将其作为字符串获取。

我想从文件中过滤一些元素,但不是从整个 php 文件中过滤,而是从 html 输出中过滤。

可以做这样的事情吗?

jcu*_*bic 5

你可以像这样使用 php 缓冲区:

<?php
ob_start();
include('other.php');
$script = ob_get_contents(); // it will hold the output of other.php
ob_end_clean();
Run Code Online (Sandbox Code Playgroud)

编辑:您可以将其抽象为一个函数:

<?php
ob_start();
include('other.php');
$script = ob_get_contents(); // it will hold the output of other.php
ob_end_clean();
Run Code Online (Sandbox Code Playgroud)