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

后端 未结 2 997
攒了一身酷
攒了一身酷 2021-01-15 15:17

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

相关标签:
2条回答
  • 2021-01-15 15:42

    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);
    
    0 讨论(0)
  • 2021-01-15 16:02

    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.

    0 讨论(0)
提交回复
热议问题