[TIPS] Write print_r() Output To File

When debugging a php application, print_r() or var_dump() often use to display the data inside the variable, usually an array that store many data inside. print_r() is core php function to displays information about a variable in a way that’s readable by humans. Not just a variable or an array, we can trace or display protected and private properties of objects in PHP 5.

But when the php application is called by the curl or other remote connection (not using a web browser), print_r() won’t show on the client as return as it won’t write 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() result 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 the file. If this what you looking for, leave any comment or at least say thanks to support me.

Comments

  1. Leigh says:

    A better way is to remove the output buffering and just use this
    $output = print_r($data, true);

  2. luiscatarino says:

    @Ivan, print_r does the exact same as var_dump() but allowing for you return the data to the variable rather than the screen. In Leigh's example, the true parameter is what tells print_r to return the data to the object.

    To use it in full to output to a file, then use the following:

    $myFile = "fileOutputName.txt";

    $fh = fopen($myFile, 'w') or die("Can't open the file");

    $results = print_r($output, true);

    fwrite($fh, $results);fclose($fh);

    • @luiscatarino I'm afraid it is not the same. var_dump have more details with data type. and print_r just output and array of data. but they are both almost work the same. and have the same goal, debug.

Give me your feedback

This site uses Akismet to reduce spam. Learn how your comment data is processed.