I'd like to capture the output of var_dump
to a string.
The PHP docs say;
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).
Can someone give me 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.
Also
echo json_encode($dataobject);
might be helpfulFrom http://htmlexplorer.com/2015/01/assign-output-var_dump-print_r-php-variable.html:
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:
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.Use output buffering:
here is the complete solution as function.
You may also try to use
serialize()
function, sometimes it very useful for debuging puprposes.