How can I capture the result of var_dump to a string?

后端 未结 13 1631
挽巷
挽巷 2020-11-27 08:39

I\'d like to capture the output of var_dump to a string.

The PHP documentation says;

As with anything that outputs its result directly to the

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 09:21

    From http://htmlexplorer.com/2015/01/assign-output-var_dump-print_r-php-variable.html:

    var_dump and print_r functions can only output directly to browser. So the output of these functions can only retrieved by using output control functions of php. Below method may be useful to save the output.

    function assignVarDumpValueToString($object) {
        ob_start();
        var_dump($object);
        $result = ob_get_clean();
        return $result;
    }
    

    ob_get_clean() can only clear last data entered to internal buffer. So ob_get_contents method will be useful if you have multiple entries.

    From the same source as above:

    function varDumpToErrorLog( $var=null ){
        ob_start();                    // start reading the internal buffer
        var_dump( $var);          
        $grabbed_information = ob_get_contents(); // assigning the internal buffer contents to variable
        ob_end_clean();                // clearing the internal buffer.
        error_log( $grabbed_information);        // saving the information to error_log
    }
    

提交回复
热议问题