I need to build a “export as .csv” functionality into my plugin. Problem is: i get the header already sent warning, because by the time my “export” function is called, WordPress has already started rendering.
The way i set it up is via a small form in the Settings screen, which action attribute points to a file (download.csv.php) in my plugin folder, that should not be shown, just prompt a file download dialog for the csv dump.
Here is my code.
In my plugin Settings screen:
<form method="post" id="download_form" action="<?php echo plugins_url( 'download.csv.php' , __FILE__ ); ?>">
<input type="hidden" name="download" value="<?php echo get_home_path(); ?>" />
<input type="submit" name="download_csv" class="button-primary" value="<?php _e('Download the log (.csv)', $this->localizationDomain); ?>" />
</form>
And the download.csv.php file:
$core = $_POST['download'].'wp-load.php';
if(isset($_POST['download']) && is_file($core)){
require_once( $core );
global $wpdb;
$rows = $wpdb->get_results('SELECT * FROM `'.$this->dbName.'`;',ARRAY_A);
if($rows){
require_once('classes/csvmaker.class.php');
$CSV = new CSVMaker();
$CSVHeader = array();
$CSVHeader['id'] = "ID";
$CSVHeader['when'] = "WHEN";
$CSVHeader['who'] = "WHO";
$CSVHeader['description'] = "DESCRIPTION";
$CSVHeader['type'] = "TYPE";
foreach($rows as $r){
$CSV->addEntry($r);
}
$file_name = plugin_dir_path(__FILE__).'data.csv';
file_put_contents($file_name,$CSV->buildDoc);
ob_start();
header("Expires: Mon, 1 Apr 1974 05:00:00 GMT");
header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/CSV");
header("Content-Disposition: attachment; filename=$file_name.csv");
echo $CSV->buildDoc;
return ob_get_clean();
exit;
}
What am i doing wrong?