创建一个数组数组以提供CSV功能

时间:2012-05-22 20:27:37

标签: php mysql csv

我正在尝试从查询中创建CSV,我需要数据符合以下格式:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

$array = array(
    array("data11", "data12", "data13"),
    array("data21", "data22", "data23"),
    array("data31", "data32", "data23"));
outputCSV($array);

我习惯于聚合这样的数据:

while ($row = mysql_fetch_array($result)){
    $values[]   = $row['value'];
}

如何将outputCSV传递给合适的数组?

3 个答案:

答案 0 :(得分:4)

function outputCSV($rows, $fieldNames = array())
{
    if ($fp = fopen('php://output', 'w')) {
        if ($fieldNames) {
            fputcsv($fp, $fieldNames);
        }
        foreach ($rows as $row) {
            fputcsv($fp, $row);
        }
        fclose($fp);
    }
}

答案 1 :(得分:1)

循环$array,呼叫fputcsv()

foreach ($array as $fields) fputcsv(STDOUT, $fields);

答案 2 :(得分:0)

$values = array();

while ($row = mysql_fetch_array($result)) {
    $values[]   = $row;
}

outputCSV($values);