Thanks; that fixes the header errors ... but it's still dumping the data to the browser rather than prompt for downloading it as a file. I've added the code below, if no one sees anything I guess I'll just format it as a table on the page and let the admin print it. Note: the shortcodes are for Paid Memberships Pro, the membership plugin I'm using, and I've activated the fpassthru function for the application on the server.
/*
Purpose: Export member neighborhood data as a CSV file.
Author: Vasily Ingogly
Date: November 14, 2023
*/
function sjotl_list_export_neighborhoods_shortcode( $attrs = null ) {
$userlist = get_users(); // Get list of WP_user objects
$delimiter = ",";
$today = date("mdY");
$csvname = "neighborhooddata-" . $today . ".csv";
$csvheader = array('MEMBER', 'LOGIN', 'NEIGHBORHOOD', 'EMAIL');
$header1 = 'Content-Type: text/csv';
$header2 = 'Content-Disposition: attachment; filename="' . $csvname . '"';
$fp = fopen('php://memory', 'w'); // Hold data in memory
$returnstring = "";
fputcsv($fp, $csvheader, $delimiter);
$numusers = 0;
foreach ($userlist as &$current_user) { // Get each user's data
$numusers++;
$neighborhood_shortcode = '[pmpro_member field="neighborhoods" user_id="' . $current_user->id . '"]';
$email_shortcode = '[pmpro_member field="user_email" user_id="' . $current_user->id . '"]';
$username = $current_user->display_name; // Member
$usernicename = $current_user->user_nicename; // Login
$userneighborhood = do_shortcode( $neighborhood_shortcode ); // Neighborhood
$useremail = do_shortcode( $email_shortcode ); // Email
$memberdata = array($username, $usernicename, $userneighborhood, $useremail);
fputcsv($fp, $memberdata, $delimiter);
unset($current_user);
}
if ($numusers != 0) {
fseek($fp, 0); // Rewind file and add headers
header("$header1");
header("$header2");
$nchars = fpassthru($fp);
fclose($fp);
} else {
fclose($fp);
$returnstring = '<br>No user data found.<br>';
}
return $returnstring;
}
add_shortcode('sjotl_list_export_neighborhoods', 'sjotl_list_export_neighborhoods_shortcode');