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

问题描述 投票:0回答:1

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

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

<?php echo "Hello"; ?> world!

但是,我不想在包含文件时打印

Hello world!
,而是想将其作为字符串获取。

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

可以做这样的事情吗?

php include
1个回答
6
投票

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

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

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

function inlcude2string($file) {
    ob_start();
    include($file);
    $output = ob_get_contents(); // it will hold the output of $file
    ob_end_clean();
    return $output;
}

$str = inlcude2string('other.php');
© www.soinside.com 2019 - 2024. All rights reserved.