0

I have made a custom plugin, which exports MYSQL table contents into a .csv file which gets saved in to wp uploads directory. Now, I am trying to give a download link for downloading directly a .csv file. But, I am getting this error "Warning: Cannot modify header information - headers already sent"

I'm so very grateful for all of the help you all give. I've searched for this topic and couldn't find it, if this topic is already answered here, please comment with the link to the question with the answer.

Thanks.

Code Which I tried for Downloaing:

header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
header( "Content-Length: " . strlen( $out ) );

// Output to browser with appropriate mime type, you choose ;)
header( "Content-type: text/x-csv" );
header( "Content-Disposition: attachment; filename=$filename" );

echo $out;
exit;
5
  • 1
    Have you seen this?
    – fuxia
    Commented Jun 24, 2013 at 7:31
  • Where are you putting this code? It won't work after any HTML has been sent to the browser.
    – shea
    Commented Jun 24, 2013 at 9:36
  • Now i have used the link as suggested by toscho by using it the errors are eliminated but download is not happening.I am just giving the link to download in the page where i want to download. Commented Jun 24, 2013 at 9:44
  • The answer toscho linked to is exactly what you're after, what part is causing confusion? Commented Jun 24, 2013 at 10:32
  • In add_action( 'admin_post_print.csv', 'print_csv' ); we are passing "admin_post_print.csv" as a name of action and what action we are specifying is "action=print.csv" in href. So i am confused in both of these. Can you please clear my confusion. Thanks Commented Jun 24, 2013 at 11:02

1 Answer 1

1

In your plugin main file eg.... my-plugin-def.php

Add the following lines

add_action( 'admin_post_sample_data.csv', 'sample_data_csv' );

function sample_data_csv()
{
    if ( ! current_user_can( 'manage_options' ) )
        return;

    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename=example.csv');
    header('Pragma: no-cache');

    // output the CSV data
    echo 'id,name';
    echo '1,Saran';
}

Where you required download link add this line

echo '<a href="' . admin_url( 'admin-post.php?action=sample_data.csv' ) . '">Download sample</a>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.