0

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?

0

2 Answers 2

1

This function is fine as long as you pass an array to second parameter. Check if you have any output like echo or print before the header().

Sign up to request clarification or add additional context in comments.

Comments

0

You are missing an exit(); at the end of the header call

see: Will PHP script be executed after header redirect?

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.