1

我正在尝试从查询创建 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适当的数组?

4

3 回答 3

5
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);
    }
}
于 2012-05-22T20:39:31.123 回答
1

循环你的$array,调用fputcsv()

foreach ($array as $fields) fputcsv(STDOUT, $fields);
于 2012-05-22T20:39:00.297 回答
0
$values = array();

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

outputCSV($values);
于 2012-05-22T20:39:40.517 回答