Php 下载到codeigniter中的CSV
我正在为我的公司构建一个搜索功能,作为这一功能的一部分,管理团队可以使用我制作的搜索表单生成搜索,这是一个视图,将各种术语发送到控制器方法Php 下载到codeigniter中的CSV,php,codeigniter,csv,Php,Codeigniter,Csv,我正在为我的公司构建一个搜索功能,作为这一功能的一部分,管理团队可以使用我制作的搜索表单生成搜索,这是一个视图,将各种术语发送到控制器方法执行搜索,它通过我的搜索模型从数据库中获取结果,并在视图中输出它们。作为其中的一部分,我有一个“下载”按钮,我想将结果导出到CSV。我做了一个控制器功能: function convert_to_csv($results) { /** open raw memory as file, no need for temp files */ $te
执行搜索
,它通过我的搜索模型
从数据库中获取结果,并在视图中输出它们。作为其中的一部分,我有一个“下载”按钮,我想将结果导出到CSV。我做了一个控制器功能:
function convert_to_csv($results)
{
/** open raw memory as file, no need for temp files */
$temp_memory = fopen('php://memory', 'w');
/** loop through array */
foreach ($results as $line) {
/** default php csv handler **/
fputcsv($temp_memory, $line);
}
/** rewrind the "file" with the csv lines **/
fseek($temp_memory, 0);
/** modify header to be downloadable csv file **/
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="Statistics_system_report.csv";');
/** Send file to browser for download */
fpassthru($temp_memory);
}
function convert_to_csv()
{
/** retrieve the search results */
$results = $this->session->flashdata('results');
/* ....... */
}
我在下载的CSV文件中发现错误,称$results
未定义
我的问题是,将结果发送到此函数的最佳方式是什么,但仅当我的用户单击下载按钮时才执行该函数?我试过这个:
$this->convert_to_csv($results)代码>
作为我的execute\u search
函数的一部分,但每次执行搜索时都会下载它,任何指向正确方向的指针都会很好。好的,所以我解决了这个问题,可能有更好的方法,但我做的是:
在控制器中:
public function __construct()
{
parent::__construct();
$this->load->library('session'); // Load sessions
/* ..... */
}
然后在我的execute\u search
功能中设置flashdata:
$this->session->set_flashdata('results', $results);
然后在我的导出功能中:
function convert_to_csv($results)
{
/** open raw memory as file, no need for temp files */
$temp_memory = fopen('php://memory', 'w');
/** loop through array */
foreach ($results as $line) {
/** default php csv handler **/
fputcsv($temp_memory, $line);
}
/** rewrind the "file" with the csv lines **/
fseek($temp_memory, 0);
/** modify header to be downloadable csv file **/
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="Statistics_system_report.csv";');
/** Send file to browser for download */
fpassthru($temp_memory);
}
function convert_to_csv()
{
/** retrieve the search results */
$results = $this->session->flashdata('results');
/* ....... */
}
问题是,如果我不止一次下载它,在清除flashdata时,CSV文件中会出现PHP错误
如果有人有更好的解决办法,我洗耳恭听。干杯
/*编辑*/
为了避免任何错误,我在我的export_To_csv
函数末尾重置了flashdata,如下所示:
// Reset the results in flash data
$this->session->set_flashdata('results', $results);
同样,这不是一个很好的实践,但现在解决了我的问题:)最佳解决方案将是PHPExcel库,因此,请继续使用它,而不是通过修补来解决此问题;) 那么,在调用方法之前,您是否检查了$result
是什么,即此调用$this->convert_to_csv($results)代码>是,它是模型中的多维数组,是$query->get()->result_array()的结果代码>谢谢你的建议,我将研究这个库,因为它可能是一个有用的资源;)