简体   繁体   中英

Change columns headers names and reordercolumns in csv file in PHP

I have a CSV file and I want, via PHP, to change columns header names and reorder columns.

I tried this but this wont work for me:

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

Kindly try this.

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

I found the some kind fo solution This will remove first row with columns names and put it in new csv file and add new columns names in the old one.

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

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