I am trying to generate a csv file from a PHP array and then to download the file right after it has been generated.
This is the function I am using:
    function generate_csv($array, $mode) 
    {
        // setting the content type of the downloadable file
        header('Content-Type: text/x-csv; charset=utf-8');
        // setting the header to offer the 'save as' dialog box
        header('Content-Disposition: attachment; filename="' . $mode . '.csv";');
        // disabling caching of the file
        header("Pragma: no-cache");
        // opening the "output" stream
        $f = fopen('php://output', 'w');
        // generate csv for repeat transactions report
        if($mode == 'repeat_transactions_csv')
        {
            // writing headers to the csv file
            fputcsv($f, array('Firstname', 'Surname', 'Email', 'Cellphone', 'Date Joined', 'First Trans.', 'Last Trans.', 'Orders'));
            // iterating through the array of data
            foreach ($array as $line) 
            {
                // formatting the date as on reports (10-Jan-14)
                $dateJoined = date('d-M-y', $line['timestamp']);
                $firstTrans = date('d-M-y', $line['first_transactions']);
                $lastTrans = date('d-M-y', $line['last_transactions']);
                // manipulating the csv values that needs to be written to the csv
                $csv_line = "{$line['firstname']},{$line['lastname']},{$line['email']},{$line['phone']},{$dateJoined},{$firstTrans},{$lastTrans},{$line['order_ids']}";
                // writing the contents of the array to the csv file
                fputcsv($f, explode(',', $csv_line));
            }
        }
        // closing the "output" stream
        fclose($f);
    }
After opening this file, I see html code underneath my actual values and looks as if the current page's html code is written to the CSV file.
Am I doing something wrong in the function?
 
     
    