I am working on a plugin that creates a menu in wp-admin / side and shows a table with some data. I need to create a CSV (this will be correct) and let the user download it automatically. I know that I have to add headers like these
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="' . $csv_file_name . '"');
But unfortunately, this does not work for the WordPress admin. Again - CSV generation is going right, but it only displays the text of the csv file under the table, but does not give the file
Here is the complete code
if ( isset( $_REQUEST['export_csv'] ) ) {
global $wpdb;
$csv_source_array = $wpdb->get_results ( $wpdb->prepare( " SELECT name, email, time, text FROM {$table_name} " ), ARRAY_N );
$csv_file_name = 'nba.rally.'.date(Ymd).'.csv';
$csv_header_array = array( "Name", "Email", "Date", "Message" );
if (isset($csv_source_array)) {
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="' . $csv_file_name . '"');
ob_start();
$f = fopen('php://output', 'w') or show_error("Can't open php://output");
$n = 0;
if (isset($csv_header_array)) {
if ( !fputcsv($f, $csv_header_array, ';'))
{
echo "Can't write line $n: $line";
}
}
foreach ($csv_source_array as $line)
{
$n++;
if ( !fputcsv($f, $line, ';'))
{
echo "Can't write line $n: $line";
}
}
fclose($f) or show_error("Can't close php://output");
$csvStr = ob_get_contents();
ob_end_clean();
echo $csvStr;
}
}
Thanks for the advance payment for any answers.
source
share