4

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 2

6

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);
Sign up to request clarification or add additional context in comments.

Comments

5

Instead of reinventing the wheel, you can use php's inbuilt csv functions fgetcsv and fputcsv respectively to ease your work. First read in each row with fgetcsv and store the data in a multidimensional array:

$delimiter = "\t"; //your column separator
$csv_data = array();
$row = 1;
if (($handle = fopen('test.csv', 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
        $csv_data[] = $data;
        $row++;
    }
    fclose($handle);
}

Next edit the rows to add the extra columns using array_merge:

$extra_columns = array('column3' => 1, 'column4' => 2);
foreach ($csv_data as $i => $data) {
    if ($i == 0) {
        $csv_data[$i] = array_merge($data, array_keys($extra_columns));
    } else {
        $csv_data[$i] = $data = array_merge($data, $extra_columns);
    }
}

Finally use fputcsv to enter each row into the csv.

if (($handle = fopen('test.csv', 'w')) !== FALSE) {
    foreach ($csv_data as $data) {
        fputcsv($handle, $data, $delimiter);
    }
    fclose($handle);
}

You can combine these steps to make your code more efficient by reducing the number of loops.

1 Comment

How to adapt your code to concatenate the values of two columns of the csv file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.