PHP:如何使用 fputcsv 在 csv 文件的顶部添加新的一行


PHP: How can I add newly one row at the top of the csv file using fputcsv?

我想如何在csv文件的顶部添加新的一个新行,以防在我的csv文件输出中填充了数据库中的数据,我想发生的是我想为每种类型的数据添加相应的列名。

这是我目前的代码:

    <?php
include 'database.php';
$db = new database();
$data = $db->exportdatabase();
$file = fopen('php://output', 'w');
foreach ($data as $items)
{
    fputcsv($file, $items, ',');
}
header('Content-Description: File Transfer');
header("Content-Type: application/csv") ;
header("Content-Disposition: attachment; filename=data.csv");
header("Expires: 0");
fclose($file);
exit;
?>

这是我的csv数据看起来像

图像

您可以在之前尝试设置列名

或使用fseek函数

fseek($file, 0);
fputcsv($file, $titles, ',');

fseek 在文件指针上查找