Write PHP Array as debug output to a file instead of echoing it

PHP debugging made easy

At some point in our life as PHP developer, we come to the point where we are debugging PHP by checking the values of our variables, arrays and objects.
We all know: Its easy to debug in Javascript. You can do something like:
console.log("variable is:"+myVar);

This is a problem for PHP debug.
You can echo() in your code, but thats not always possible.
Output thats printed in a controller action often disappeares from the screen when the site is rendered.
Sometimes the very own debug function of your framework overwrites everything we tried to display.
Sometimes your layout will break, or when doing AJAX calls you might not even see anything.
So how can you see your precious variables, objects and SQL commands at runtime without breaking the app?

A way to debug some values is writing them to a file.


$myVariable = "Hey, Mr. Coder!";

$debugfile = fopen("debug.txt", "w");

fwrite($debugfile, $myVariable."\n");


Or for an Array:

$myArray = ['color' => 'green','feet' => 'big','dog' => 'Retriever'];

$debugfile = fopen("debug.txt", "w");

fwrite($debugfile, print_r($myArray, true));


You should notice the “w” in the fopen command. This is called the “mode”. Mode “w” means your file will always be cleared when writing to it.
If you dont want that, but rather keep all records in the file, you should use mode “a”:

$debugfile = fopen("debug.txt", "a");

Do you see the “\n” in the first fwrite command? This writes a newline to the file. Otherwise the following array would be written to the same line as the variable and the whole debug output would be hardly readable.

For a list of all modes and more examples you should head over to https://php.net/manual/de/function.fopen.php.