[TIPS] Write print_r() Output To File

When debugging a PHP application, print_r() or var_dump() is often used to display the data inside a variable, usually an array that stores many values. print_r() is a core PHP function that displays information about a variable in a human-readable way. Not just variables or arrays — we can also trace or display protected and private properties of objects in PHP 5.

But when a PHP application is called by curl or another remote connection (not using a web browser), print_r() won’t show on the client since it won’t be written as output. So to debug a remote application, I often write the result or output from print_r() to a debug file.

To write print_r() output we need to use output buffering. See the example:

$data = array('one', 'two', 'three');
ob_start(); //Start buffering
print_r($data); //print the result
$output = ob_get_contents(); //get the result from buffer
ob_end_clean(); //close buffer

$h = fopen('log.txt', 'w'); //open a file
fwrite($h, $output); //write the output text
fclose($h); //close file

This is a simple trick to write the output of print_r() to a file. If this is what you were looking for, leave a comment or at least say thanks to support me.