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 Solution
Try
var_exportYou may want to check out
var_export— while it doesn't provide the same output asvar_dumpit does provide a second$returnparameter which will cause it to return its output rather than print it:Why?
I prefer this one-liner to using
ob_startandob_get_clean(). I also find that the output is a little easier to read, since it's just PHP code.The difference between
var_dumpandvar_exportis thatvar_exportreturns a "parsable string representation of a variable" whilevar_dumpsimply dumps information about a variable. What this means in practice is thatvar_exportgives 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_exportin above example):var_dump (
$debug_dumpin above example):print_r (
$debug_printrin above example):Caveat:
var_exportdoes not handle circular referencesIf you're trying to dump a variable with circular references, calling
var_exportwill result in a PHP warning:Results in:
Both
var_dumpandprint_r, on the other hand, will output the string*RECURSION*when encountering circular references.