CSV Import Row Normalizer
Normalizes one CSV data row into named fields by using a validated header position map.
Purpose
Normalizes one CSV data row into named fields by using a validated header position map.
Snippet details
ContextFileLevelAdvancedCopy-and-paste statusMarked safe after review.Categories
- Security
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* CSV Import Row Normalizer.
*
* Purpose:
* Converts a numeric CSV row into an associative record using a known column
* position map and trims string values without hiding missing fields.
*
* @param array $csv_row Numeric CSV row from fgetcsv or another reader.
* @param array $position_map Column name to numeric row offset map.
* @param array $required_columns Required column names that must contain values.
* @return array Normalized row data and row-level errors.
*/
function ogSnippetCsvImportRowNormalizer(array $csv_row, array $position_map, array $required_columns): array {
$record = array();
$errors = array();
foreach ($position_map as $field_name => $offset) {
$value = '';
if (isset($csv_row[$offset]) === true) {
$value = trim((string) $csv_row[$offset]);
}
$record[$field_name] = $value;
}
foreach ($required_columns as $field_name) {
$clean_name = strtolower(trim((string) $field_name));
if ($clean_name === '') {
continue;
}
if (isset($record[$clean_name]) === false) {
$errors[] = 'Required field "'.$clean_name.'" is not mapped.';
} elseif ($record[$clean_name] === '') {
$errors[] = 'Required field "'.$clean_name.'" is empty.';
}
}
return array(
'valid' => count($errors) === 0,
'record' => $record,
'errors' => $errors
);
}
$position_map = array(
'ship_id' => 0,
'captain' => 1,
'registry' => 2,
'sector' => 3
);
$csv_row = array('RZ-001', 'Malcolm Reynolds', 'Serenity', 'Kalidasa');
$normalized = ogSnippetCsvImportRowNormalizer($csv_row, $position_map, array('ship_id', 'captain', 'registry'));
if ($normalized['valid'] === true) {
echo 'Firefly CSV row normalized for '.$normalized['record']['ship_id'].'.';
} else {
echo 'Firefly CSV row needs review.';
}