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.
Best Answer
Try
var_export
You may want to check out
var_export
— while it doesn't provide the same output asvar_dump
it does provide a second$return
parameter which will cause it to return its output rather than print it:Why?
I prefer this one-liner to using
ob_start
andob_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
andvar_export
is thatvar_export
returns a "parsable string representation of a variable" whilevar_dump
simply dumps information about a variable. What this means in practice is thatvar_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:
The difference in output:
var_export (
$debug_export
in above example):var_dump (
$debug_dump
in above example):print_r (
$debug_printr
in above example):Caveat:
var_export
does not handle circular referencesIf you're trying to dump a variable with circular references, calling
var_export
will result in a PHP warning:Results in:
Both
var_dump
andprint_r
, on the other hand, will output the string*RECURSION*
when encountering circular references.