CSV文件仅包含HTML页面代码

时间:2014-07-11 13:38:55

标签: php csv export-to-csv

我正在尝试从PHP数组生成csv文件,然后在生成文件后立即下载该文件。

这是我正在使用的功能:

    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);
    }

打开此文件后,我会在实际值下看到html代码,看起来好像当前页面的html代码已写入CSV文件。

我在功能上做错了吗?

2 个答案:

答案 0 :(得分:1)

只要将数组传递给第二个参数,此函数就可以了。 检查echo之前是否有printheader()之类的输出。

答案 1 :(得分:0)

标头调用结束时您缺少exit();

请参阅:Will PHP script be executed after header redirect?