在 PHP 的 csv 文件中更改列 headers 名称并重新排序列

Change columns headers names and reordercolumns in csv file in PHP

我有一个 CSV 文件,我想通过 PHP 更改列 header 名称并对列重新排序。

我试过了,但这对我不起作用:

function toCSV($data, $outstream) {
    if (count($data)) {
        // get header from keys
        fputcsv($outstream, array_keys($data[0]));
        // 
        foreach ($data as $row) {
            fputcsv($outstream, $row);
        }
    }
}

请试试这个。

$inputCsv = 'sample.csv';
$outputCsv = 'output.csv';

$inputHandle = fopen($inputCsv, 'r');
$header = fgetcsv($inputHandle);


/*
 * 1. For name change
 */
$header[0] = 'column 1 name changed here';
$header[2] = 'column 3 name changed here';

 /*
     * 2. For header order change I am shuffling column names
 */
shuffle($header);

 $outputHandle = fopen($outputCsv, 'w');
 fputcsv($outputHandle, $header);


while($row = fgetcsv($inputHandle)){
    fputcsv($outputHandle, $row);
}

fclose($outputHandle);

我找到了某种解决方案 这将删除带有列名称的第一行并将其放入新的 csv 文件中,并在旧文件中添加新的列名称。

$old_file = 'X.csv';
$new_file = 'testdata_new.csv';

$file_to_read = file_get_contents($old_file);  // Reading entire file
$lines_to_read = explode("\n", $file_to_read);  // Creating array of lines

if ( $lines_to_read == '' ) die('EOF'); // No data 

$line_to_append = array_shift( $lines_to_read ); // Extracting first line 

$file_to_append = file_get_contents($new_file);  // Reading entire file

if ( substr($file_to_append, -1, 1) != "\n" ) $file_to_append.="\n";  // If new file doesn't ends in new line I add it

// Writing files
file_put_contents($new_file, $file_to_append . $line_to_append . "\n");
file_put_contents($old_file, implode("\n", $lines_to_read));



  $header = "here write the names  \r\n";
  $data = file_get_contents($old_file);
  file_put_contents($old_file, $header.$data);