我正在尝试从查询中创建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
传递给合适的数组?
答案 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);