0

I am trying to write a CSV file by getting data from the database and store into and array. However I am getting the following error 4 times (for each header();)

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\dizz\wp-includes\formatting.php:5081) in C:\xampp\htdocs\dizz\wp-content\plugins\Report\index.php on line 46

My code:

<?php
/*
Plugin Name: Export Mailing List
*/
function custom_admin_menu(){
    add_menu_page( 
        'Export Mailing List',
        'Export Mailing List',
        'edit_posts',
        'export_mailing_list',
        'custom_export_mailing_list',
        'dashicons-media-spreadsheet'
    ); 
}
add_action( 'admin_menu', 'custom_admin_menu' );

function custom_export_mailing_list() {
    GenerateEmails();
}

function GenerateEmails(){

    $mailingList = array();
    $thisEmail = array();

    global $wpdb;
    $the_query = $wpdb->get_results( "SELECT * FROM wp_subscribers");

    foreach($the_query as $sub){ 
        $thisEmail = array(
            'Full Name' => $sub->Fullname,
            'Email' => $sub->Email,
            'DOB' => $sub->DOB,
            'Address' => $sub->Address,
            'Address 2' => $sub->Address2,
            'City' => $sub->City,
            'Postcode' => $sub->Postcode,
            'Telephone' => $sub->Telephone,
            'Mobile' => $sub->Mobile
        );
        array_push($mailingList, $thisEmail);
    }

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-Description: File Transfer');
    header("Content-Type: text/csv; charset=UTF-8");
    header("Content-Disposition: attachment; filename=EmailList.csv");

    echo "<h1>Downloading Mailing List...</h1>";
    //    header("Expires: 0");
    //    header("Pragma: public");
    //echo "\xEF\xBB\xBF"; // UTF-8 BOM

    $fh = @fopen( 'php://output', 'w' );

    $headerDisplayed = false;

    foreach ( $mailingList as $data ) {
        // Add a header row if it hasn't been added yet

        if ( !$headerDisplayed ) {

            fputcsv($fh, array_keys($data));
            $headerDisplayed = true;
        }

        // Put the data into the stream
        fputcsv($fh, $data);
    }
    // Close the file
    fclose($fh);
}
?>

P.S I am already using this code in another project without any problems in regards to headers. There do no seem any whitespace issues.

anton
  • 1

0 Answers0