capturing echo into a variable

后端 未结 3 682
广开言路
广开言路 2020-12-13 09:15

I am calling functions using dynamic function names (something like this)

$unsafeFunctionName = $_POST[\'function_name\'];
$safeFunctionName   = safe($unsafe         


        
相关标签:
3条回答
  • 2020-12-13 09:45

    In order to use the output value, if present, or the return value if not, you could simply modify your code like this:

    ob_start();
    $return_val = $safeFunctionName();
    $echo_val = ob_get_clean();
    $result = "<return_value>" . (strlen($echo_val) ? $echo_val : $return_val) . "</return_value>";
    
    0 讨论(0)
  • 2020-12-13 09:50

    PHP: ob_get_contents

    ob_start(); //Start output buffer
    echo "abc123";
    $output = ob_get_contents(); //Grab output
    ob_end_clean(); //Discard output buffer
    
    0 讨论(0)
  • 2020-12-13 09:55

    Let me preface this by saying:

    Be careful with that custom function calling business. I am assuming you know how dangerous this can be which is why you're cleaning it somehow.

    Past that, what you want is known as output buffering:

    function hello() {
        print "Hello World";
    }
    ob_start();
    hello();
    $output = ob_get_clean();
    print "--" . $output . "--";
    

    (I added the dashes to show it's not being printed at first)

    The above will output --Hello World--

    0 讨论(0)
提交回复
热议问题