Output variables PHP, print or echo variables using PHP, Can’t print contents of variable to screen PHP

Hi Quick blog on how to print PHP variables whilst debugging.

If you are using PHP classes in a framework such as Joomla you may find that you are unable to see PHP variables stored in classes whilst debugging. Because the server side PHP code within a PHP class is hidden from view in the browser you have got no chance of using a print or echo statement.

This is how I managed to print the contents of the variables I was working with.
I created a file for writing in the directory which presents the web content eg /var/www/html (see code example below)

$myFile = “/var/www/html/manage/testFile.txt”;
$fh = fopen($myFile, ‘w’) or die(“can’t open file”);

I then created a string which contains the data which will be handed to the file handler and hence written to the file. Notice that I used the var_export command when outputting the contents of the variable. You are unable to use print, echo or var_dump for this (so this is the magic bit that you need to remember… var_export). Note that there is an additional argument passed (true). This argument called “return” which is set to true simply returns the variable representation to the string which stores it whilst being passed to the file handler for writing.

$stringData = “Options \n” . var_export($options, true) . “\n”;
fwrite($fh, $stringData);

Remember to close the file handler in your code like this.


Once we have printed the data to the file system we can read it using the tail command.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s