PHP – Write an Array/Object to File by print_r()

In debugging PHP program, i always use print() and print_r() to output the variable content to the browser. But this does not work when we are not using browser. A simple way to get the content is to write it to a file.

I found a nice post written by Ivan which provides this simple way with just a few lines of code.
Ivan Kristianto – [TIPS] Write print_r() Output To File

<?php
  $data = array('one', 'two', 'three');
  $fh = fopen('log.txt', 'w') or die("Can't open file.");
  // output the value as a variable by setting the 2nd parameter to true
  $results = print_r($data, true);
  fwrite($fh, $results);
  fclose($fh);
?>

 

Done =)

Reference: Ivan Kristianto – [TIPS] Write print_r() Output To File

2 thoughts on “PHP – Write an Array/Object to File by print_r()”

Leave a comment

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