PHP capture print/require output in variable

后端 未结 2 817
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 03:04

Is it possible to add the output of print() to a variable?

I have the following situation:

I have a php file which looks something like this:

2条回答
  •  不知归路
    2020-12-07 03:38

    You can capture output with the ob_start() and ob_get_clean() functions:

    ob_start();
    print("abc");
    $output = ob_get_clean();
    // $output contains everything outputed between ob_start() and ob_get_clean()
    

    Alternatively, note that you can also return values from an included file, like from functions:

    a.php:

    return "";
    

    b.php:

    $html = include "a.php"; // $html will contain ""
    

提交回复
热议问题