Possible to capture PHP echo output?

前端 未结 2 1156
南旧
南旧 2021-01-01 16:17

So I have a function such as:

public static function UnorderedList($items, $field, $view = false){
    if(count($items) > 0){
        echo \'
    \'
相关标签:
2条回答
  • 2021-01-01 16:38

    Very Similar to previous answer but a little more concise for my purposes:

    <?php
    ob_start(); // Start output buffering
    
    Render::UnorderedList(Class::getItems(), Class::getFields(), true); 
    
    $list = ob_get_clean(); // Store buffer AND cleans it
    
    echo $list; // will contain the contents
    ?>
    

    I also want to mention how useful this is for PHP unit testing so as not to clutter your test logs with the output of what you are testing unless the test fails. Here is another stackflow answer related to this because I found this answer first on my google search when I was looking at how to test items with echo output : How to use output buffering inside PHPUnit test?

    0 讨论(0)
  • 2021-01-01 16:47

    Yes, using output buffering.

    <?php
    ob_start(); // Start output buffering
    
    Render::UnorderedList(Class::getItems(), Class::getFields(), true); 
    
    $list = ob_get_contents(); // Store buffer in variable
    
    ob_end_clean(); // End buffering and clean up
    
    echo $list; // will contain the contents
     ?>
    
    0 讨论(0)
提交回复
热议问题