2017-02-28 77 views
0

我想从我的数据库使用内置的PHP函数fputcsv()下载简单的CSV文件。尝试下载从我的数据库创建的CSV文件时出错

这里是我的功能:

/** 
* downloads class logs in csv format 
*/ 
public function ajaxDownloadTeachersClassLogs() 
{ 
    // ...code to get data from the database... 
    $classes = $query->result(); 

    // download file 
    header("Content-Type: text/csv"); 
    header("Content-Disposition: attachment; filename=file.csv"); 

    // write data to file 
    $output = fopen("php://output", "w"); 
    foreach ($classes as $class) { 
     fputcsv($output, $class); 
    } 
    // change delimiter/enclosure 
    fclose($output); 
} 

我知道,我的数据库查询是正确的,因为当我var_dump($classes);我得到以下结果:

array(1) { 
    [0]=> 
    object(stdClass)#26 (10) { 
    ["token"]=> 
    string(5) "9DFCF" 
    ["teacher_name"]=> 
    string(17) "James Dean" 
    ["teacher_id"]=> 
    string(1) "2" 
    ["student_name"]=> 
    string(11) "Juan Santos" 
    ["student_id"]=> 
    string(2) "26" 
    ["class_number"]=> 
    string(3) "1/1" 
    ["started"]=> 
    string(10) "1488279490" 
    ["duration"]=> 
    string(4) "1200" 
    ["invite_email"]=> 
    string(0) "" 
    ["status"]=> 
    string(0) "" 
    } 
} 

当我跑我得到函数如下错误:

enter image description here

如果我点击确定,下载失败。

为什么我的下载失败?

编辑:

它看起来像我的问题是与内容编码错误我这是在我所用的框架错误配置套管做...

以下作品的代码:

$this->db->order_by('started'); 
$query = $this->db->get('classes'); 

header('Content-Type: application/csv'); 
header('Content-Disposition: attachment; filename=data.csv;'); 

$flag = false; 
$output = fopen('php://output', 'w'); 
foreach ($query->result_array() as $row) { 
    if ($flag === false) { 
     fputcsv($output, array_keys($row), ','); 
    } 
    fputcsv($output, array_values($row), ','); 
} 
die; 
+0

你可以这样使用。 $ fp = fopen('file.csv','w'); fputcsv($ fp,$ data); –

回答

1

请尝试以下步骤:

  • 首先用一些硬编码数据做一个CSV,检查是否出现同样的问题。
  • 如果有那么硬编码的数据出现问题的剧照:

    $output = fopen("php://output", "w");

,而不是这个写在一些项目directory文件,看看会发生什么。

+0

对,仍然得到硬编码数据的错误...问题可能是你的第二个建议 –

+0

尝试第二个选项,然后让我知道会发生什么 –

+0

嗨,Mayank,我错了,第一个选项实际工作,我相信,问题是我得到我的数据库结果广告一个关联数组,但它需要是一个数组数组!谢谢你的帮助! –

1

您可以使用内置的fputcsv()来为您的阵列生成正确的csv行,因此您必须循环并收集这些行。如:

// open raw memory as file so no temp files needed, you might run out of memory though 
    $f = fopen('php://memory', 'w'); 
    // loop over the input array 
    foreach ($classes as $class) { 
     fputcsv($output, $class); 
    } 
    // reset the file pointer to the start of the file 
    fseek($f, 0); 
    // tell the browser it's going to be a csv file 
    header('Content-Type: application/csv'); 
    // tell the browser we want to save it instead of displaying it 
    header('Content-Disposition: attachment; filename="'.$filename.'";'); 
    // make php send the generated csv lines to the browser 
    fpassthru($f); 
相关问题