开发者

Possible to capture PHP echo output?

开发者 https://www.devze.com 2023-01-20 04:02 出处:网络
So I have a function such as: public static function UnorderedList($items, $field, $view = false){ if(count($items) > 0){

So I have a function such as:

public static function UnorderedList($items, $field, $view = false){
    if(count($items) > 0){
        echo '<ul>';
        foreach($items as $item){
            echo '<li>';
            if($view){
                echo '<a href="'.$view.'id='.$item->sys_id.'" title="View Item">'.$item->$field.'</a>';
            }else{
                echo $item->$field;
            }   
            echo '</li>';
        }
        echo '</ul>'; 
    }else{
        echo '<p>No Items...</p>';
    }
}

This function loops over some items and renders a unordered list. What I am wondering is 开发者_Go百科if its possible to capture the echo output if I wish.

I make a call to use this function by doing something like:

Render::UnorderedList(Class::getItems(), Class::getFields(), true); 

And this will dump a unordered list onto my page. I Know I can just change echo to a variable and return the variable but I was just curious if its possible to capture echo output without modifying that function, merely modifying the call to the function in some way?

Thanks!


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
 ?>


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

精彩评论

暂无评论...
验证码 换一张
取 消