Add 2 new column header and contents in csv file using php

Viewed 5752

I've an existing csv file with following values

column1 column2
Fr-fc   Fr-sc
Sr-fc   Sr-sc

I want to add 2 new columns in it and achieve the following format

column1 column2 column3 column4
Fr-fc   Fr-sc     1        2
Sr-fc   Sr-sc     1        2

If I use following code it inserts same column header value in column data for the newly created columns

$a = file('amit.csv');// get array of lines
$new = '';
foreach($a as $line){
    $line = trim($line);// remove end of line
    $line .=";column3";// append new column
    $line .=";column4";// append new column
    $new .= $line.PHP_EOL;//append end of line
}
file_put_contents('amit2.csv', $new);// overwrite the same file with new data

How I can achieve the above?

2 Answers
Related