tags:

views:

1591

answers:

5

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.

+18  A: 

Use output buffering:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
Eran Galperin
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.
Techpriester
+2  A: 

You could also do this:

$dump = print_r($variable, true);
Ian P
Doesn't work for objects
Eran Galperin
He never specified objects. Thanks for the downvote, though :)
Ian P
I did specifically mention var_dump though :)
Mark Biek
I didn't downvote ...
Eran Galperin
I'm just being factitious.. I'm not mad.. lol
Ian P
+1 for a one-line alternative.
scotts
+3  A: 

You could also use var_export($var, true); -- but that probably won't give you all the information you need.

inxilpro
That's interesting. I wasn't aware of that function.
Mark Biek
+1  A: 

You may also try to use serialize() function, sometimes it very useful for debuging puprposes.

Sergei Stolyarov
A: 

If you want to have a look at a variables 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.

Techpriester