How do I capture the result of an echo() into a variable in PHP?

前端 未结 4 736
攒了一身酷
攒了一身酷 2020-12-19 12:31

I\'m using a PHP library that echoes a result rather than returns it. Is there an easy way to capture the output from echo/print and store it in a variable? (Other text has

相关标签:
4条回答
  • 2020-12-19 12:48

    You should really rewrite the class if you can. I doubt it would be that hard to find the echo/print statements and replace them with $output .=. Using ob_xxx does take resources.

    0 讨论(0)
  • 2020-12-19 13:06

    You could use output buffering :

    ob_start();
    
    function test ($var) {
        echo $var;
    }
    
    test("hello");
    $content = ob_get_clean();
    
    var_dump($content); // string(5) "hello"
    

    But it's not a clean and fun syntax to use. It may be a good idea to find a better library...

    0 讨论(0)
  • 2020-12-19 13:09

    The only way I know.

    ob_start();
    echo "Some String";
    $var = ob_get_clean();
    
    0 讨论(0)
  • 2020-12-19 13:10

    Its always good practise not to echo data until your application as fully completed, for example

    <?php
    echo 'Start';
    
    session_start();
    ?>
    

    now session_start along with another string of functions would not work as there's already been data outputted as the response, but by doing the following:

    <?php
    $output = 'Start';
    
    session_start();
    
    echo $output;
    ?>
    

    This would work and its less error prone, but if its a must that you need to capture output then you would do:

    ob_start();
    
    //Whatever you want here
    
    $data = ob_get_contents();
    
    //Then we clean out that buffer with:
    ob_end_clean();
    
    0 讨论(0)
提交回复
热议问题