You’ve got a few things wrong.
- The first is that you are clearly in WordPress context. You should
be using the AJAX API for this rather than includingwp-load.php
.
That is virtually never the right way to do it. get_results()
defaults to an object, so you are going to get
errors when you try to use the results as an array. AddARRAY_A
to
the argument list for that function (or use object syntax)- Don’t hard-code the WordPress table prefix
$file
isn’t defined- You have two queries when you only need one
- Your
foreach
andfor
, and associated code, is far too
complicated.
I don’t have your table to test with but this should be close.
function csv_pull_wpse_212972() {
global $wpdb;
$file="email_csv"; // ?? not defined in original code
$results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}email_table;",ARRAY_A);
if (empty($results)) {
return;
}
$csv_output=""".implode('";"',array_keys($results[0])).'";'."\n";;
foreach ($results as $row) {
$csv_output .= '"'.implode('";"',$row).'";'."\n";
}
$csv_output .= "\n";
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
}
add_action('wp_ajax_csv_pull','csv_pull_wpse_212972');
To “trigger” this send a request to http://sitename.com/wp-admin/admin-ajax.php?action=csv_pull
. Within WordPress you can generate that (and should generate that) with $ajax_url = admin_url('admin-ajax.php?action=csv_pull');