输出到CSV生成错误

时间:2014-03-03 19:17:10

标签: php mysql csv

我在使用fputcsv功能方面没有太多经验。 我正在尝试创建一个功能,管理员可以通过该功能下载包含所有用户信息的文件。

应以这种方式生成CSV:

Serial Number   Username     Email    etc etc

然后查询记录。

我有这个函数,我用它来生成csv文件:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // 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 ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // rewrind the "file" with the csv lines
    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: attachement; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}

然后我调用函数:

<?php
include 'inc/inc.functions.php';
include 'dbconnector.php';
$query="SELECT * from users order by email LIMIT 0,30";
$result=mysql_query($query,$db) or die(mysql_error($db));
$array=mysql_fetch_array($result);

foreach($array as $arr)
{
array_to_csv_download($arr,"records.csv",":");
}

?>

生成的CSV显示:Warning, Invalid argument supplied for foreach.

我该怎么做以我需要的方式展示?

更新

http://i.imgur.com/2xH0gT1.png

1 个答案:

答案 0 :(得分:0)

您当前正在为数据库中的单行调用函数,而不是整个结果集。以下内容应正确使用您的功能:

$query = "SELECT * from users order by email LIMIT 0,30";
$result = mysql_query($query,$db) or die(mysql_error($db));
$array = array();

# Headers
$array[] = array("Serial Number","Username","Email","etc etc");

while($row = mysql_fetch_row($result)) {
    $array[] = $row;
}
array_to_csv_download($array,"records.csv",":");