Capture the output of var_dump in a string

Introduction

You are programming in PHP and you have an array variable that you’d like to explore at different execution paths. Of course, the best way is to use a PHP debugger like xdebug or Zend Debugger, but, what happens when you’re too lazy to install a debugger? What happens when you don’t want or can’t install a debugger and you just need to check the content of that array by dumping it in your log file? Well, you might think you’re stuck, but, read on…

What is var_dump?

The var_dump manual page states that var_dump displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

The problem is that var_dump outputs its result directly to the browser, how can you capture its output in a string variable? read on…

Using output control functions for the solution

Output control functions can be used to capture and redirect the standard output. For more details, read the PHP manual on output control functions, of course.

Here’s the solution:

function varDumpToString ($var)
{
    ob_start();
    var_dump($var);
    $result = ob_get_clean();
    return $result;
}
//
//Example usage:
//    $data = array('first', 'second', 'third');
//    $result = varDumpToString($data);
//

All you have to do now is call the varDumpToString function. Happy coding :)



Leave a Reply