简体   繁体   中英

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

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?

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM