使用 php 在 csv 文件中添加 2 个新列标题和内容

2023-12-09

我有一个包含以下值的现有 csv 文件

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

我想在其中添加 2 个新列并实现以下格式

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

如果我使用以下代码,它将在新创建的列的列数据中插入相同的列标题值

$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

我怎样才能实现上述目标?


这种方法代码量少

<?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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 php 在 csv 文件中添加 2 个新列标题和内容 的相关文章