PHP capture print/require output in variable

后端 未结 2 806
隐瞒了意图╮
隐瞒了意图╮ 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:33

    You can use output buffering to capture any output send ob_start() http://us3.php.net/ob_start. You capture the output with ob_get_flush() http://us3.php.net/manual/en/function.ob-get-flush.php.

    Or you could just return the output from title.php like so:

    <?php
    
    $content = '<h1>Page heading</h1>';
    return $content;
    
    0 讨论(0)
  • 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 "<html>";
    

    b.php:

    $html = include "a.php"; // $html will contain "<html>"
    
    0 讨论(0)
提交回复
热议问题