Reputation: 313
Need to process large csv files with php. Working with fgetcsv and performance seems pretty good. For even better/ faster processing I would like the csv files to have column names on the first row, which are missing right now.
Now I would like to add a top row with columns names to the csv file with PHP before processing the files with fgetcsv.
Is there a way to add a line top the top of the file with php easily? Or would this mean I have to take a approach like below?
Any feedback on how to do this in the most effective way is highly appreciated. Thanks for your time :)
Upvotes: 2
Views: 6697
Reputation: 248
Please try this .. much simpler and straight to the point.
$file = 'addline.csv';
$header = "Name, IP, Host, RAM, Task, NS \r\n";
$data = file_get_contents($file);
file_put_contents($file, $header.$data);
You are done. Hope this helps...
Upvotes: 3
Reputation: 2844
Why not to define header in your code manually, especially if every file has the same header?
If you really need to insert header into CSV files before you process them maybe you should consider using sed like this: sed -i 1i'"header 1","header 2"' file.csv
Upvotes: 0
Reputation: 4042
Just do it the way you provided. there is no easy way to extend a file on the beginning instead of the end. it's like writing on paper. it's easy to add new lines below your text but you can't write above you text.
Don't use fopen($file, "r+")
or fopen($file, "c")
as this will remove existing lines at the beginning or even all lines of your file.
Upvotes: 1
Reputation: 1035
Upvotes: 2