创建CSV并强制下载文件

时间:2015-01-11 14:52:22

标签: php csv

我有这个PHP代码,它从数据库中选择数据并创建一个CSV文件。

它的工作正常,但是如何在完成创建后强行下载CSV文件?

我已在页面顶部添加了标题,但未下载文件

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

$filename = $SettingsCustomer["company"].'-CallsTariff'.'-'.date("YmdHis");

// create a file pointer connected to the output stream
$output = fopen($_SERVER["DOCUMENT_ROOT"].'/file_dump/price_tariffs/'.$filename.'.csv', 'w');

// output the column headings
fputcsv($output, array('Number', 'Description', 'Per Minute Cost'));

// loop over the rows, outputting them
$cost=0;
$sql="SELECT * from call_costs where sequence < '50' ";
$rs=mysql_query($sql,$conn);
while($result = mysql_fetch_array($rs)) {
    //check for custom costs
    $sql2="SELECT * from call_costs_custom where parent = '".$result["sequence"]."' AND customer_seq = '".$SettingsCustomer["sequence"]."' ";
    $rs2=mysql_query($sql2,$conn);
    if(mysql_num_rows($rs2) > 0) {
        $result2=mysql_fetch_array($rs);

        $cost = $result2["cost"];
    } else {
        $cost = $result["retail"];
    }

    fputcsv($output, array($result["number"], $result["description"], $cost));
}

3 个答案:

答案 0 :(得分:3)

Charlie,这是一种创建和强制下载到csv文件的示例方法。尝试在代码中实现这一点:

<?php

$filename = 'test';

$filepath = $_SERVER["DOCUMENT_ROOT"] . $filename.'.csv';
$output = fopen($filepath, 'w+');

fputcsv($output, array("Number", "Description", "test"));
fputcsv($output, array("100", "testDescription", "10"));

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
header('Content-Length: ' . filesize($filepath)); 
echo readfile($filepath);

答案 1 :(得分:1)

请在下次更好地搜索。每次都是相同的答案

header('Content-Type: application/octet-stream');

text / csv是一个可显示的内容类型

答案 2 :(得分:0)

嗯,你需要在最后......

$file = '/file_dump/price_tariffs/'.$filename.'.csv';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;

您可以删除get_content_file