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

PhpStringVar Dump

Php Problem Overview


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 browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

What would be an example of how that might work?

print_r() isn't a valid possibility, because it's not going to give me the information that I need.

Php Solutions


Solution 1 - Php

Try var_export

You may want to check out var_export — while it doesn't provide the same output as var_dump it does provide a second $return parameter which will cause it to return its output rather than print it:

$debug = var_export($my_var, true);

Why?

I prefer this one-liner to using ob_start and ob_get_clean(). I also find that the output is a little easier to read, since it's just PHP code.

The difference between var_dump and var_export is that var_export returns a "parsable string representation of a variable" while var_dump simply dumps information about a variable. What this means in practice is that var_export gives you valid PHP code (but may not give you quite as much information about the variable, especially if you're working with resources).

Demo:

$demo = array(
    "bool" => false,
    "int" => 1,
    "float" => 3.14,
    "string" => "hello world",
    "array" => array(),
    "object" => new stdClass(),
    "resource" => tmpfile(),
    "null" => null,
);

// var_export -- nice, one-liner
$debug_export = var_export($demo, true);

// var_dump
ob_start();
var_dump($demo);
$debug_dump = ob_get_clean();

// print_r -- included for completeness, though not recommended
$debug_printr = print_r($demo, true);

The difference in output:

var_export ($debug_export in above example):

 array (
  'bool' => false,
  'int' => 1,
  'float' => 3.1400000000000001,
  'string' => 'hello world',
  'array' => 
  array (
  ),
  'object' => 
  stdClass::__set_state(array(
  )),
  'resource' => NULL, // Note that this resource pointer is now NULL
  'null' => NULL,
)
var_dump ($debug_dump in above example):
 array(8) {
  ["bool"]=>
  bool(false)
  ["int"]=>
  int(1)
  ["float"]=>
  float(3.14)
  ["string"]=>
  string(11) "hello world"
  ["array"]=>
  array(0) {
  }
  ["object"]=>
  object(stdClass)#1 (0) {
  }
  ["resource"]=>
  resource(4) of type (stream)
  ["null"]=>
  NULL
}
Array
(
    [bool] => 
    [int] => 1
    [float] => 3.14
    [string] => hello world
    [array] => Array
        (
        )

    [object] => stdClass Object
        (
        )

    [resource] => Resource id #4
    [null] => 
)

Caveat: var_export does not handle circular references

If you're trying to dump a variable with circular references, calling var_export will result in a PHP warning:

 $circular = array();
 $circular['self'] =& $circular;
 var_export($circular);

Results in:

 Warning: var_export does not handle circular references in example.php on line 3
 array (
   'self' => 
   array (
     'self' => NULL,
   ),
 )

Both var_dump and print_r, on the other hand, will output the string *RECURSION* when encountering circular references.

Solution 2 - Php

Use output buffering:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>

Solution 3 - Php

You could also do this:

$dump = print_r($variable, true);

Solution 4 - Php

if you are using PHP>=7.0.0

function return_var_dump(...$args): string
{
    ob_start();
    try {
        var_dump(...$args);
        return ob_get_clean();
    } catch (\Throwable $ex) {
        // PHP8 ArgumentCountError for 0 arguments, probably..
        // in php<8 this was just a warning
        ob_end_clean();
        throw $ex;
    }
}

or if you are using PHP >=5.3.0:

function return_var_dump(){
    ob_start();
    call_user_func_array('var_dump', func_get_args());
    return ob_get_clean();
}

or if you are using PHP<5.3.0 (this function is actually compatible all the way back to PHP4)

function return_var_dump(){
    $args = func_get_args(); // For <5.3.0 support ...
    ob_start();
    call_user_func_array('var_dump', $args);
    return ob_get_clean();
}

(prior to 5.3.0 there was a bug with func_get_args if used directly as an argument for another function call, so you had to put it in a variable and use the variable, instead of using it directly as an argument..)

Solution 5 - Php

You may also try to use the serialize() function. Sometimes it is very useful for debugging purposes.

Solution 6 - Php

Also echo json_encode($dataobject); might be helpful

Solution 7 - Php

From the PHP manual:

> This function displays structured information about one or more expressions that includes its type and value.

So, here is the real return version of PHP's var_dump(), which actually accepts a variable-length argument list:

function var_dump_str()
{
    $argc = func_num_args();
    $argv = func_get_args();

    if ($argc > 0) {
        ob_start();
        call_user_func_array('var_dump', $argv);
        $result = ob_get_contents();
        ob_end_clean();
        return $result;
    }

    return '';
}

Solution 8 - Php

If you want to have a look at a variable's contents during runtime, consider using a real debugger like XDebug. That way you don't need to mess up your source code, and you can use a debugger even while normal users visit your application. They won't notice.

Solution 9 - Php

Here is the complete solution as a function:

function varDumpToString ($var)
{
    ob_start();
    var_dump($var);
    return ob_get_clean();
}

Solution 10 - Php

This maybe a bit off topic.

I was looking for a way to write this kind of information to the Docker log of my PHP-FPM container and came up with the snippet below. I'm sure this can be used by Docker PHP-FPM users.

fwrite(fopen('php://stdout', 'w'), var_export($object, true));

Solution 11 - Php

I really like var_dump()'s verbose output and wasn't satisfied with var_export()'s or print_r()'s output because it didn't give as much information (e.g. data type missing, length missing).

To write secure and predictable code, sometimes it's useful to differentiate between an empty string and a null. Or between a 1 and a true. Or between a null and a false. So I want my data type in the output.

Although helpful, I didn't find a clean and simple solution in the existing responses to convert the colored output of var_dump() to a human-readable output into a string without the html tags and including all the details from var_dump().

Note that if you have a colored var_dump(), it means that you have Xdebug installed which overrides php's default var_dump() to add html colors.

For that reason, I created this slight variation giving exactly what I need:

function dbg_var_dump($var)
    {
        ob_start();
        var_dump($var);
        $result = ob_get_clean();
        return strip_tags(strtr($result, ['=&gt;' => '=>']));
    }

Returns the below nice string:

array (size=6)
  'functioncall' => string 'add-time-property' (length=17)
  'listingid' => string '57' (length=2)
  'weekday' => string '0' (length=1)
  'starttime' => string '00:00' (length=5)
  'endtime' => string '00:00' (length=5)
  'price' => string '' (length=0)

Hope it helps someone.

Solution 12 - Php

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 }

Solution 13 - Php

Long string: Just use echo($var); instead of dump($var);.

Object or Array: var_dump('<pre>'.json_encode($var).'</pre>);'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark BiekView Question on Stackoverflow
Solution 1 - PhpinxilproView Answer on Stackoverflow
Solution 2 - PhpEran GalperinView Answer on Stackoverflow
Solution 3 - PhpIan PView Answer on Stackoverflow
Solution 4 - PhphanshenrikView Answer on Stackoverflow
Solution 5 - PhpSergey StolyarovView Answer on Stackoverflow
Solution 6 - PhpZurabWebView Answer on Stackoverflow
Solution 7 - PhpYounis BensalahView Answer on Stackoverflow
Solution 8 - PhpselfawaresoupView Answer on Stackoverflow
Solution 9 - PhpKhandad NiaziView Answer on Stackoverflow
Solution 10 - PhpCharlie VieillardView Answer on Stackoverflow
Solution 11 - PhpWadih M.View Answer on Stackoverflow
Solution 12 - PhpDev CView Answer on Stackoverflow
Solution 13 - PhpvuchkovView Answer on Stackoverflow