【问题标题】:Include a php file, but return output as a string instead of printing包含一个 php 文件,但将输出作为字符串而不是打印返回
【发布时间】:2017-01-18 09:23:13
【问题描述】:

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

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

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

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

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

有可能做这样的事情吗?

【问题讨论】:

  • 是的,使用output buffering;或者通过修改你的文件来返回一个值而不是回显它
  • @Mark Ba​​ker,但是如果我使用 ob,它还会打印输出吗?
  • 使用输出缓冲会将回显值放在输出缓冲区中,而不是将其发送到显示...。这取决于您随后对该输出缓冲区的内容执行的操作...和这可以包括将它移动到一个变量而不是显示它......这就是输出缓冲的全部意义
  • 好的,我认为即使在缓冲时它也会打印。我会尝试。谢谢

标签: php include


【解决方案1】:

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

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

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

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

$str = inlcude2strig('other.php');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2014-09-22
    • 2022-01-22
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多