How I have solved the “The plugin generated xxxx characters of unexpected output during activation” problem

Recently this problem troubled me a lot. All time I try to activate my plugin, I get the following error:

The plugin generated 1186 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

After several attempts of debugging, I failed to understand why it is coming. The mysterious thing was that, this error was not coming for all WordPress installations!

Today, I decided to read the core files those are responsible for activating and/or deactivating the plugins. When I was reading wp-admin/includes/plugin.php, I saw a action hook ‘activated_plugin’ is available just before throwing the error. I believed, if I monitor what is happening here, I can know the reason of the error. So I wrote a small function to save the errors like:

add_action('activated_plugin','save_error');
function save_error(){
    update_option('plugin_error',  ob_get_contents());
}

Then, I tried re-activating my plugin and I believed the error is saved in the wordpress option table. Now I need to see what happened. In my plugin page, I put these codes:

echo get_option('plugin_error');

Then what I found what is causing the error. It was holding the what you see on the image.

It was like bolt to me. Why the hell was it coming! Then I again looking at my source and I saw I have included a wrong file.

For using dbDelta we have to include the file in following way:

 require_once ABSPATH.'wp-admin/includes/upgrade.php';

but I included a wrong file by:

 require_once ABSPATH.'wp-admin/upgrade.php';

As the filename was same, I confused with path and included wrong and it taken me several days to solve it.

However, I have solved it. I believe, if you ever face any such problems with your plugin, you can find the output texts using the above methods. If you have better methods, please share with me. I would simply love to know.