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

1

1

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

Echinoderm answered 25/1, 2013 at 1:49 Comment(2)
What's the problem? Write the line of column names before the foreach loop.Molasses
that's my problem I don't know how? :(Echinoderm
D
2

You can try before foreach set column names

Or using fseek function

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

fseek Seeks on a file pointer

Detect answered 25/1, 2013 at 1:58 Comment(4)
Can you seek in php://output? It doesn't point to a file. But why do you need to seek? Just do it before writing the data.Molasses
where should i put my title? for example i have a column name of "ID", "BRAND", "PRICE" and etc..? where should i put that got confused. thanks!Echinoderm
@Echinoderm $columns = array('id', 'brand', 'price', ...); before foreach loop put this array to output, like this: fputcsv($file, $columns, ',');Detect
@Molasses I just provide an example. :)Detect

© 2022 - 2024 — McMap. All rights reserved.