Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array-to-CSV-export function is facing an issue in WordPress-plugin

I am using a simple array-to-CSV-export function in my plugin page for generating a report .

When I am running this code I am getting an error that it will export whole html content along with my expected array.

Here is my code:

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
    clearstatcache();
    /** open raw memory as file, no need for temp files */
    $temp_memory = fopen('php://memory', 'w');
    /** loop through array  */



    foreach ($input_array as $line) {
        /** default php csv handler **/
        fputcsv($temp_memory, $line, $delimiter);
    }

    //echo '<pre>';
    //print_r($temp_memory); exit;
    /** rewrind the "file" with the csv lines **/
    fseek($temp_memory, 0);
    /** modify header to be downloadable csv file **/
    header('Content-Type: application/csv');
    header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
    /** Send file to browser for download */
    fpassthru($temp_memory);
}

/** Array to convert to csv */

$array_to_csv = Array(
    Array(12566,
        'Enmanuel',
        'Corvo'
    ),
    Array(56544,
        'John',
        'Doe'
    ),
    Array(78550,
        'Mark',
        'Smith'
    )

);

clearstatcache();

convert_to_csv($array_to_csv, 'report.csv', ',');
like image 965
dipanjan chakraborty Avatar asked Apr 23 '15 07:04

dipanjan chakraborty


1 Answers

I'm guessing that WP is carrying on with its normal operations after this function is called so you'll get the HTML template output after the CSV. Putting in an exit statement after fpassthru should do it, but you need to be careful that this doesn't mess up anything else that Wordpress does at the end of each page response. Drupal for example has a drupal_exit() function for just this purpose. I'm not familiar enough with WP to know for sure, but the documentation for the wp_die() function suggests that you can use PHP exit without too many problems

like image 85
james-geldart Avatar answered Oct 23 '22 17:10

james-geldart