UBB.Dev
Posted By: Dave_L_dup1 Capturing var_dump output in a file - 03/19/2003 2:02 AM
The PHP var_dump() function is handy for debugging. In a web script, it's not always practical or desirable to send debug output to the browser, so I spent the time figuring out how to redirect the output to a file. Here's an example:

Code
<?php <br /> <br />echo "testing capture of var_dump output<br />\n"; <br /> <br />// test data <br />$a = array( <br />   'x' => 'x_value', <br />   'y' => 'y_value', <br />   array( <br />      'z' => 'z_value', <br />      'w' => 'z_value' <br />   ), <br />); <br /> <br />// output-file <br />define ('OB_LOG', 'ob_test.log'); <br /> <br />// clear output-file if it exists (optional) <br />if (file_exists(OB_LOG)) { <br />   unlink(OB_LOG); <br />} <br /> <br />// method 1 - output buffer explicitly <br />ob_start(); <br />echo "test 2\n"; <br />echo "a=\n"; <br />var_dump($a); <br />error_log(ob_get_contents(), 3, OB_LOG); <br />ob_end_clean(); <br /> <br />// method 2 - use callback function to output buffer <br />ob_start('callback'); <br />echo "test 1\n"; <br />echo "a=\n"; <br />var_dump($a); <br />ob_end_flush(); <br /> <br />echo "done<br />\n"; <br /> <br />// callback function for ob_start() - only needed if using method 2 <br />function callback($buf) { <br />   error_log($buf, 3, OB_LOG); <br />   return ''; <br />} <br /> <br />?>


Outputting the buffer explicitly (method 1) is simpler, but using a callback function (method 2) might be preferable if you're doing the output in several places.
© UBB.Developers