Reformat A CSV File In PHP

CSV ingestion can be annoying as users will tend to add random columns to the data before they hand it over. Use the following script to reformat the CSV file.

<?php

$fileName = 'csv_file_from_user.csv';

$correctedCsv = 'corrected.csv';
$correctedCsvHandle = fopen($correctedCsvHandle, 'w');

// Set to FALSE if the header row isn't present.
$header = TRUE;

if ($handle = fopen($fileName, 'r')) {
  while ($line = fgetcsv($handle, 4096)) {
    if ($header === TRUE) {
      // Skip header row.
      $header = FALSE;
      continue;
    }
	
    // If the data isn't correct then we skip the row.
    // For example, if column 8 isn't present then the data is blank so we skip.
    if (!isset($line[8]) || trim($line[8]) == '') {
      continue;
    }

    // Reformat the CSV file columns. Here, we take column 0 and column 8 from the
    // user csv and write them together in a single CSV file.
    $writeMe = [
      $line[0],
      $line[8],
    ];
    
    // Filter the array to remove any blank rows and reject if it's empty after that step.
    $writeMe = array_filter($writeMe);
    if (count($writeMe) !== 2) {
      continue;
    }

    // Write the the output CSV.
    fputcsv($correctedCsvHandle, $writeMe);
  }
  fclose($handle);
}
else {
  echo 'Input file not present.';
}

fclose($correctedCsvHandle);

Run this script from the command line.

This is more or less and emergency measure, when you just have to convert the CSV file from one format to another in short order and you can't fiddle with the spreadsheet itself. You might want to start asking questions about why this or that row was skipped.

Add new comment

The content of this field is kept private and will not be shown publicly.