Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download exported csv file in Wordpress

I work on the plugin that creates menu in wp-admin/ side and shows the table with some data. I need to generate CSV ( it's going correct ) and give user to donwload it automatically. I know, that I have to add the headers like these

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="' . $csv_file_name . '"');

But unfortunately it does not work for wordpress admin-side. Again - the generating of CSV is going correct, but it displays just a text of csv file below the table, but don't give the file

Here is full code

if ( isset( $_REQUEST['export_csv'] ) ) {
        global $wpdb;
        $csv_source_array = $wpdb->get_results ( $wpdb->prepare( " SELECT name, email, time, text FROM {$table_name} " ), ARRAY_N );
        $csv_file_name = 'nba.rally.'.date(Ymd).'.csv';
        $csv_header_array = array( "Name", "Email", "Date", "Message" );        

            if (isset($csv_source_array)) {

                header('Content-type: application/csv');
                header('Content-Disposition: attachment; filename="' . $csv_file_name . '"');

            ob_start();
                $f = fopen('php://output', 'w') or show_error("Can't open php://output");
                $n = 0;


                    if (isset($csv_header_array)) {
                        if ( !fputcsv($f, $csv_header_array, ';'))
                        {
                            echo "Can't write line $n: $line";
                        }
                    }

                foreach ($csv_source_array as $line)
                {
                    $n++;

                    if ( !fputcsv($f, $line, ';'))
                    {
                        echo "Can't write line $n: $line";
                    }
                }
                fclose($f) or show_error("Can't close php://output");
                $csvStr = ob_get_contents();
                ob_end_clean();

                echo $csvStr;
            }


        }   

Thanks for an advance for any answers.

like image 931
Maksym Avatar asked Nov 05 '22 11:11

Maksym


1 Answers

I have fixed it.

I've inserted that code on the top of the plugin.

I think because the headers should send on the head of script and before load document or after tag.

Note:

The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.

from php.net/manual/en/function.header.php

like image 118
Maksym Avatar answered Nov 09 '22 10:11

Maksym