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

14

684

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.

Blueweed answered 26/9, 2008 at 13:23 Comment(1)
I know it's passed some time but I've read this in the question: "is not going to give me the information that I need". So, it may be useful to add in the question what information you need.Alten
S
656

Use output buffering:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
Spirant answered 26/9, 2008 at 13:25 Comment(8)
Using output buffering will most likely have a negative effect on performance here. It also can get really messy if you need to look at multiple variables during the execution of a complex script.Behn
@Inwdr I've only ever used var_dump as a convenience feature for debugging, and have certainly never left var_dump statements in production code. I imagine this is typical. In those circumstances, performance is unlikely to be at all relevant.Delvecchio
also remove the tags for readability (if you just want the string), using strip_tags(), this will simply return the type and value.Helyn
This is a good literal answer to the question, as you're 'captur[ing] the result of a var_dump to a string' exactly like what was asked. var_export() is a better answer in spirit, as it makes more sense generally.Hawley
@AlbertHendriks Well, in extrict terms, the question is asking about the function named var_dump. We both know that var_export it is better, but as the user didn't know about it when asking we are in that point. As you can see, the answer below with var_export has much more upvotes now. This situation it is so tipycal in many other scenarios, because usually people don't know to ask better, or puts more importance on what they do than to what they need... but well, learning to create objects will not hurt you (others) so much, and you'll see the proper response below at the same price :-)Campanula
@AlbertHendriks I prefer var_dump. With Xdebug enabled you get a pretty data displaying.Anjelicaanjou
This is the perfect answer. The var_export answer is long-winded and irrelevant, since it uses neither var_dump nor output capture, and var_export, like print_r, doesn't give types.Selfcentered
Even the PHP's var_dump documentations recommends capturing the string with output controls.Virgenvirgie
L
974

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
}

print_r ($debug_printr in above example):

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.

Laid answered 26/9, 2008 at 13:38 Comment(9)
Thanks! Used to use print_r, but this is way better for debugging. error_log(var_export($var, true)); All you need! :)Bemuse
This is definitely a better answer than the accepted one. I'm surprised it doesn't have more upvotes! Could you elaborate on why it might not give all the information he's looking for?Cyanide
@Cyanide var_export returns a parsable string—essentially PHP code—while var_dump provides a raw dump of the data. So, for example, if you call var_dump on an integer with the value of 1, it would print int(1) while var_export just prints out 1.Laid
var_export lands on its belly if you use it with $GLOBALS while var_dump works.Audacity
won't work with variables containing references to itself.. var_export does not work like var_dump; like this, $v=[];$v[]=&$v;var_export($v,true); ...Bromleigh
Stop hyping people. var_export isn't actually better for debugging because you couldn't do a browser search for (int) or (string)` and etc. It also mangles alot of information into a small space, just try: var_export(''); var_export('\'');. And most importantly, get ready for PHP Fatal error: Nesting level too deep - recursive dependency? in C:\path\file.php on line 75Fraxinella
@Fraxinella For me the first point is a benefit. I think it just comes down to preference. The circular reference issue is a good point, though. I've added a comment about it to my response.Laid
+1 @Fraxinella this answer is worse, cause it substitutes the main question "how to catch result to string" by "how to dump variables other way"Phthalocyanine
This is definitely the worse answer. OP almost certainly asked about var_dump over print_r because var_dump gives type information, whereas print_r and var_export do not. This answer also muddies the waters by using type names as key names, unintentionally making it look (at least at first glance) as if var_export actually does give type information. IMO this is misleading, doesn't answer OP, and should have <0 votes.Selfcentered
S
656

Use output buffering:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
Spirant answered 26/9, 2008 at 13:25 Comment(8)
Using output buffering will most likely have a negative effect on performance here. It also can get really messy if you need to look at multiple variables during the execution of a complex script.Behn
@Inwdr I've only ever used var_dump as a convenience feature for debugging, and have certainly never left var_dump statements in production code. I imagine this is typical. In those circumstances, performance is unlikely to be at all relevant.Delvecchio
also remove the tags for readability (if you just want the string), using strip_tags(), this will simply return the type and value.Helyn
This is a good literal answer to the question, as you're 'captur[ing] the result of a var_dump to a string' exactly like what was asked. var_export() is a better answer in spirit, as it makes more sense generally.Hawley
@AlbertHendriks Well, in extrict terms, the question is asking about the function named var_dump. We both know that var_export it is better, but as the user didn't know about it when asking we are in that point. As you can see, the answer below with var_export has much more upvotes now. This situation it is so tipycal in many other scenarios, because usually people don't know to ask better, or puts more importance on what they do than to what they need... but well, learning to create objects will not hurt you (others) so much, and you'll see the proper response below at the same price :-)Campanula
@AlbertHendriks I prefer var_dump. With Xdebug enabled you get a pretty data displaying.Anjelicaanjou
This is the perfect answer. The var_export answer is long-winded and irrelevant, since it uses neither var_dump nor output capture, and var_export, like print_r, doesn't give types.Selfcentered
Even the PHP's var_dump documentations recommends capturing the string with output controls.Virgenvirgie
I
89

You could also do this:

$dump = print_r($variable, true);
Interlace answered 26/9, 2008 at 13:27 Comment(2)
I did specifically mention var_dump though :)Blueweed
I personally prefer using print_r where I can, but unfortunately sometimes it doesn't provide enough information. For instance, since it casts to string where it can, both false and null show as an empty string. In cases where I care about the difference between these, I would begrudgingly resort to var_dump or var_export.Cyanide
B
22

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..)

Bromleigh answered 10/11, 2013 at 13:44 Comment(3)
@MarkAmery Seems true. I just made it easy.Bromleigh
PHP5.6+ function vardump(...$args){if(count($args)){ob_start();var_dump(...$args);return ob_get_clean();}return '';}Lovett
@Lovett more like function vardump(...$args){if(count($args)){ob_start();var_dump(...$args);return ob_get_clean();}else{trigger_error("vardump() expects at least 1 parameter, 0 given.",E_USER_ERROR);return "";}} - for PHP<8 when you give var_dump() 0 arguments, it triggers an error, so your vardump should do the same when there's 0 arguments. but if you are using PHP>=8 it will throw an ArgumentCountError exception, so your vardump() should also do the same in php>=8..Bromleigh
H
16

Also echo json_encode($dataobject); might be helpful

Heigho answered 6/8, 2013 at 15:59 Comment(4)
In this case, output is very confusing and far away from debug purpose in my opinion.Easel
Mark Biek didn't say anything about debugging, did he? Maybe he just needs object saved in the DB. In this case my offered method would work well. Thanks for the heads up anyways, Tomáš Zato.Heigho
Anyway, json_encode will not contain all the data var_dump does (as variable types for example). json_encode outputs the same information as print_R, inly in different format.Easel
Ok, I will explain it once more. The OT stated that he needs output of var_dump. He also stated that print_R is provides insufficient information for his needs. There is no real difference in information that is provided by json_encode and print_r - only the data format is different. Given this, if print_r is insufficient, so is json_encode. Please don't complain about the downvote anymore. It obviously wasn't just random click, so deal with it.Easel
T
15

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

Titre answered 29/9, 2008 at 2:41 Comment(1)
A word of warning - if the reason you want the output as a string is to error_log it, you should not use this solution, since serialize's output can contain null bytes and error_log truncates strings containing null bytes.Delvecchio
M
13

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 '';
}
Mcewen answered 14/9, 2014 at 16:47 Comment(3)
+1 for providing the Real Answer to the actual question. I'm reading this because I need var_dump, not var_export, print_r, serialize, json_encode, or a real debugger. I know how to use those, too. OP asked for var_dump, I need var_dump. Thank you!Shevat
if you want to stay true to var_dump, you must trigger_error("Wrong parameter count for var_dump_str()"); when argc<=0 ; or better yet, have var_dump do it for you. :pBromleigh
This adds pretty much nothing that wasn't already in the accepted answer. The $argc check here is unnecessary and arguably incorrect as pointed out by @hanshenrik, and once you take that away all you're really adding is the call_user_func_array and func_get_args calls.Delvecchio
B
5

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.

Behn answered 27/12, 2009 at 16:47 Comment(0)
H
5

Here is the complete solution as a function:

function varDumpToString ($var)
{
    ob_start();
    var_dump($var);
    return ob_get_clean();
}
Harker answered 13/10, 2013 at 11:30 Comment(1)
won't work with more than 1 variable... var_dump("foo","bar") => string(3) "foo" string(3) "bar" varDumpToString("foo","bar") => string(3) "foo"Bromleigh
W
2

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));
Whity answered 2/5, 2018 at 8:49 Comment(1)
the handle is never closed tho, so this is a resource leak, which may be a problem in long-running daemon-style scripts. but try file_put_contents('php://stdout',var_export($object, true),FILE_APPEND);Bromleigh
S
1

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.

Shew answered 27/4, 2019 at 19:25 Comment(1)
In 2021, for debugging applications error logging, this is the most useful answer IMO.Zonked
L
-1

To get around the print_r shortfall, (returns a 1/0 for true/false), here's a routine to convert true/false to "var_dump" type text before sending the variable to print_r:

$arr=['name'=>'Joe','male'=>true];
$arr1=array_map(function($v){
    if(is_bool($v)){
        $v='bool('.($v?'true':'false').')';
    }
    return $v;
}, $arr);
$out = print_r($arr1,true);
echo $out;
Lynch answered 25/12, 2023 at 23:58 Comment(0)
O
-2

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
}
Overcloud answered 20/1, 2015 at 6:41 Comment(1)
Please properly indicate when you're quoting material from another source. Prior to the edit I'm about to make, the only part of this answer formatted as a quote is the part you didn't copy and paste from somebody's blog.Delvecchio
S
-3

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

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

Synthiasyntonic answered 12/8, 2019 at 2:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.