Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

csv

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?

like image 710
amitshree Avatar asked Sep 03 '25 04:09

amitshree


1 Answers

This approach is less code

<?php
$inFile = fopen('test.csv','r');
$outFile = fopen('output.csv','w');

$line = fgetcsv($inFile);
while ($line !== false) {
        $line[] = 'third column';
        $line[] = 'fourth column';
        fputcsv($outFile, $line);
        $line = fgetcsv($inFile);
}
fclose($inFile);
fclose($outFile);
like image 130
user2182349 Avatar answered Sep 04 '25 18:09

user2182349