0

Im trying to export data from bulk action in custom WP_List_Table class. I have following function for exporting data but I get "headers already sent" errors all the time i want to export data. Could you please point what I'm doing wrong?

public static function export_mailings ($data) {

    if ( !current_user_can( 'manage_options') ) {
       return;
    }

    global $wpdb;
    $filename = 'mailings-' . date('d-M-Y') . '.csv';

    $sql = "SELECT * FROM {$wpdb->prefix}wpsml WHERE `id` IN (" . implode(',', array_map('intval', $data)) . ")";
    $results = $wpdb->get_results($sql);

    $csv_headers = array();
    $csv_headers[] = 'Date';
    $csv_headers[] = 'Name';
    $csv_headers[] = 'Email';

    $filename = 'export' . date('d-M-Y');
    $output_handle = fopen('php://output', 'w');

    header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
    header( 'Content-Description: File Transfer' );
    header( 'Content-type: text/csv' );
    header( 'Content-Disposition: attachment; filename=' . $output_filename );
    header( 'Expires: 0' );
    header( 'Pragma: public' );

    fputcsv($output_handle, $csv_headers);

    foreach ($results as $result) {
        fputcsv($output_handle, (array)$result);
    }

    fclose($output_handle);
    die();
}
Shravan Sharma
  • 989
  • 8
  • 17

1 Answers1

0

It looks like you're calling this function too late, after some data is outputted. Try hooking into init:

function yourfunction() {
    dosomething();
}
add_action('init', yourfunction);

The full reference can be found here.

Alexander Mikhalchenko
  • 4,525
  • 3
  • 32
  • 56
  • This is a method of the WP_List_Table class, it gets fired when an "export" action is triggered from the bulk actions select in that admin page. – mkolodziejczak Jan 14 '16 at 13:13
  • @szamantg Well, than maybe some of this might help you: http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php – Alexander Mikhalchenko Jan 14 '16 at 13:20