gpt4 book ai didi

php - 从 codeigniter mysql 下载 csv

转载 作者:行者123 更新时间:2023-11-29 01:06:03 24 4
gpt4 key购买 nike

我想我遗漏了一些明显的东西。我正在尝试将数据集从 MySQL 查询导出到 CSV,而不将其打印到浏览器。

这是我的代码:

<?php

$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');

foreach ($list as $fields) {
fputcsv($fp, $fields);
}

$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);

?>

$stories 是我根据 MySQL 查询创建的数组。

目前,所有内容都打印到浏览器,没有错误,也没有下载,但我想强制下载 CSV。我该怎么做?


最终工作代码:

 $this->load->helper('download');

$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}

$data = file_get_contents('php://output');
$name = 'data.csv';

// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();

force_download($name, $data);
fclose($fp);

最佳答案

您可以从您的 Controller 调用模型 CSV()

$this->load->model('Users_model');
$this->Users_model->csv();

在模型中

function csv()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$query = $this->db->query("SELECT * FROM Users");
$delimiter = ",";
$newline = "\r\n";
$data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
force_download('CSV_Report.csv', $data);
}

您的文件将开始下载

关于php - 从 codeigniter mysql 下载 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20840274/

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