Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use fputcsv() to insert a row at the top of a csv file?

Tags:

php

csv

Pretty simple question. I know how to use fputcsv() to insert a row into a csv but it inserts it at the bottom. Is there a way to use it to insert something at the top of the csv?

I need to add a header to an existing csv file.

Any help on this would be great.

Thanks!

like image 710
Sequenzia Avatar asked Apr 25 '13 15:04

Sequenzia


People also ask

How does PHP Fputcsv work?

fputcsv() function in PHP The fputcsv() function formats a line as CSV and writes it to an open file. The function returns the length of the written string.

How do I store form data in a CSV file?

For make this type of system here we have use PHP script. We have use some PHP in build function like fopen() for open file for write operation, file() function for get file data in array format for count number of rows in file and fputcsv() function for write form data in csv file.

What is CSV file in PHP?

CSV stands for comma-separated values. A CSV file is a text file that stores tabular data in the form of comma-separated values. A CSV file stores each record per line. And it may have a header.


2 Answers

fputcsv() inserts data at the file pointer, so you can rewind() the pointer to the beginning of the file.

rewind($handle);
fputcsv($handle, $fields);

Alternately, you can simply open the file with the pointer at the beginning:

$handle = fopen('yourfile.csv', 'r+');
fputcsv($handle, $fields);
like image 102
George Cummins Avatar answered Oct 13 '22 00:10

George Cummins


Basically with:

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

I think this is duplicate for PHP: How can I add newly one row at the top of the csv file using fputcsv?

like image 35
TerminatorX Avatar answered Oct 13 '22 00:10

TerminatorX