gpt4 book ai didi

php - 创建 CSV 文件并强制下载文件

转载 作者:可可西里 更新时间:2023-11-01 01:00:43 24 4
gpt4 key购买 nike

我有这段从数据库中选择数据并创建 CSV 文件的 PHP 代码。

它工作正常,但是我如何在创建完成后强制下载 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));
}

最佳答案

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

关于php - 创建 CSV 文件并强制下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27888374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com