Column Mapping and Data Transformation
Translate user-facing headers into canonical fields and normalize values before validation or insertion.
Updated
suggestColumnMap()transformer()projectColumns()importToSql()What you will learn
- Create explicit, auditable column maps.
- Use mapping suggestions only as a user-assistance feature.
- Normalize strings, numbers, dates, and enums before persistence.
Start with explicit canonical fields#
$map = [
'Product Code' => 'sku',
'Product Name' => 'name',
'Unit Price' => 'price',
'Available' => 'is_active',
];Use suggestions for interactive mapping#
$suggestions = MnbExcel::suggestColumnMap(
sourceColumns: ['Product Code', 'Title', 'Selling Price'],
targetColumns: ['sku', 'name', 'price'],
aliases: [
'sku' => ['product code', 'item code'],
'name' => ['title', 'product name'],
'price' => ['selling price', 'unit price'],
],
minConfidence: 0.60
);Register a reusable transformer#
MnbExcel::transformer('normalize-product', function (array $row): array {
$row['sku'] = strtoupper(trim((string) ($row['sku'] ?? '')));
$row['name'] = trim((string) ($row['name'] ?? ''));
$row['price'] = round((float) ($row['price'] ?? 0), 2);
$row['is_active'] = in_array(
strtolower((string) ($row['is_active'] ?? '')),
['1', 'true', 'yes', 'active'],
true
);
return $row;
});Apply transformations in the import pipeline#
$result = MnbExcel::largeImportToSql($path, $pdo, 'products', [
'map' => $map,
'transformers' => ['normalize-product'],
'batch_size' => 1000,
]);Was this guide useful?Use GitHub issues for corrections, missing examples, or unclear behavior.
Open an issue