CSV file generation failing

Try this:

<?php
   header("Content-type: application/csv");
   header('Content-Disposition: inline; filename="export.csv"'); // change this filename
   include ('../../../wp-load.php'); // may need to change number of "../" depending upon location
   global $wpdb;
   $rows = $wpdb->get_results ("SELECT * FROM {$wpdb->prefix}table_name"); // change the table name
   echo strtolower(implode(',', array_keys((array)$rows[0]))) . "\r\n"; // fixes an Excel bug if the first column is "ID"
   foreach($rows as $row) echo '"' . implode ('","', array_values((array)$row)) . '"' . "\r\n";
?>

This will automatically format the entire contents of the table as a CSV and stream the download straight to browser, raising a dialog prompting the user to save the file.