Search code examples
phpcsvfopenfputcsv

Use fputcsv create a .csv file and also update the page with table data


I am using fputcsv to create a .csv file and download it automatically for the user. This works great:

function create_csv($data, $not_valid, $csv_old_count, $file_name) {

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="'.$file_name.'"');

    $fp = fopen('php://output', 'w');
    foreach ( $data as $line ) {
        fputcsv($fp, $line);
    }
    fclose($fp);
    exit();

}

But, I would also like to update the page with a table that shows the data that was put into the csv file. When trying to do this by removing exit() and adding a loop to write the table, that data also get written to the csv file instead of writing to my page.

How can I create and download the .csv and also write some HTML to the page?


Solution

  • You can add the output to your foreach() -

    foreach ( $data as $line ) {
        fputcsv($fp, $line);
        $newLines .= $line . "<br />"; // you'll have to figure out formatting
    }
    fclose($fp);
    echo $newLines; // place this where you want to display the lines