Regarding clearing the output buffer, some time ago I had a similar issue and this solved the issue, at least for me:
// Close output buffers till the level reaches 0
while (ob_get_level() > 0)
{
ob_end_clean();
}
// Start capturing output into a buffer
ob_start();
// Content to export
echo $toExport;
// Get the buffer and clear it
$fileContent = ob_get_contents();
ob_end_clean();
// Echo will start the download
echo $fileContent;