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

爱⌒轻易说出口 提交于 2019-12-08 12:37:42

问题


I want how can I add newly one new row at the top of the csv file becase in my csv file output its populated with data from database and what I want to happen is that I want to add corresponding column names for every type of data.

Here is my code as of now:

    <?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;
?>

Here is my csv data looks like

Image


回答1:


You can try before foreach set column names

Or using fseek function

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

fseek Seeks on a file pointer



来源:https://stackoverflow.com/questions/14514069/php-how-can-i-add-newly-one-row-at-the-top-of-the-csv-file-using-fputcsv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!