1

I am trying to remove unnecessary column from my csv. What i do is read from current csv and use fputcsv to produce a new one. However, the data is mess up because fputcsv add extra blank column just before $data[21]. Below is my code

$file_path = 'test.csv';
$file_output = 'new.csv';
if (file_exists($file_path) && filesize($file_path) > 0) {
    if (false !== ($read_file = fopen($file_path, 'r'))) {
        $output_file = fopen($file_output, 'w');
        while (false !== ($data = fgetcsv($read_file))) {
            $outputData = array($data[1], $data[6], $data[19], $data[20],
                $data[21]);
            fputcsv($output_file, $outputData);

        }

    }
    fclose($read_file);
    fclose($output_file);

}
John Conde
  • 217,595
  • 99
  • 455
  • 496
user1139747
  • 67
  • 1
  • 2
  • 9

2 Answers2

0

Hope you have mentioned correct sequence of array here:

 $outputData = array($data[1], $data[6], $data[19], $data[20], 
                          $data[21]);

If data index will not found/defined then fputcsv() will add extra column into new csv.

Sachin I
  • 1,500
  • 3
  • 10
  • 29
  • Hi what i did was var_dump $data variable so I could see the pointing in the array and pick the necessary position in array to write out. So there is no way one of the column i pick above is not defined. It is very strange – user1139747 Jun 03 '15 at 13:11
  • Do this way then: while(false !== ($data = fgetcsv($read_file))){ $outputData[0] = $data[1]; $outputData[1] = $data[6]; $outputData[2] = $data[19]; $outputData[3] = $data[20]; $outputData[4] = $data[21]; } fputcsv($output_file, $outputData); – Sachin I Jun 03 '15 at 13:14
  • Sure .. then let me try that – user1139747 Jun 03 '15 at 13:15
  • the last column it also get append with " and in the new line get append with with another " .. This is so strange i never seen this happen before – user1139747 Jun 03 '15 at 13:20
  • Its really strange!! Try by adding ini_set("auto_detect_line_endings", true); – Sachin I Jun 03 '15 at 13:25
  • Try by adding delimiter: fputcsv($output_file, $outputData, ','); – Sachin I Jun 03 '15 at 13:32
0

From the different column counts, it appears that the file needs deleted before you run your code. You might want to unset the file at the start of the execution.

if (file_exists($file_output)) {
    unset($file_output);
}

// continue with getting and populating CSV
Kevin Nagurski
  • 1,889
  • 11
  • 24