By Greg Nowak. Updated 22 November 2026.
A supplier’s price file should be a routine upload. It becomes an operational problem when a changed delimiter shifts the columns, a product code loses its leading zeros, or a retry creates duplicate records.
Choosing a PHP CSV parser helps, but the bigger decision is how your importer handles uncertainty. Can someone preview the changes? What happens to invalid records? Can operations safely retry a failed job without calling a developer?
I would start with who controls the file and what an incorrect import could change. Those answers give business owners and agency teams a useful basis for choosing—and estimating—the implementation.
Which PHP CSV parser should you choose?
| Your situation | Practical starting point | Work still required |
|---|---|---|
| You control the export and its format | PHP’s built-in fgetcsv() | Strict structure checks, business validation and error reporting |
| Suppliers or customers provide recurring files | League CSV | Saved import settings, encoding handling and a preview |
| You already use ParseCsv or need delimiter detection | Evaluate ParseCsv against representative files | Confirm detected settings and test the deployed PHP version |
Agree on the import rules before choosing a library
Collect real sample files before accepting an estimate. Include awkward examples: blank values, accented names, quoted descriptions containing line breaks, and repeated product codes.
Document the delimiter, encoding, required headings, date and decimal formats, and file limits. Decide whether columns can move and whether unexpected columns should block the upload.
Then settle the business rules. Does an unknown SKU create a product? Does a blank price mean “leave unchanged” or “remove the price”? Should one invalid record block everything? Keep identifiers such as SKUs and postcodes as strings. If a spreadsheet has already removed leading zeros before export, the parser cannot reliably reconstruct them.
Use built-in PHP for a predictable file format
fgetcsv() is a reasonable starting point for a controlled export. It reads records incrementally without requiring another package. The PHP manual recommends explicitly setting the escape argument to an empty string; relying on its default has been deprecated since PHP 8.4.
This skeleton expects UTF-8 without a byte-order mark (BOM), comma separators and fixed headings:
<?php
$handle = fopen('/path/to/import.csv', 'r');
if ($handle === false) {
throw new RuntimeException('Cannot open the import file.');
}
try {
$header = fgetcsv($handle, 0, ',', '"', '');
if ($header !== ['sku', 'name', 'price']) {
throw new RuntimeException('Use the supplied CSV template.');
}
$recordNumber = 1;
while (($row = fgetcsv($handle, 0, ',', '"', '')) !== false) {
++$recordNumber;
if ($row === [null]) {
continue;
}
if (count($row) !== count($header)) {
throw new RuntimeException(
"Record {$recordNumber}: expected three fields."
);
}
$record = array_combine($header, $row);
// Validate business values, then stage this record.
}
if (!feof($handle)) {
throw new RuntimeException('The import file could not be fully read.');
}
} finally {
fclose($handle);
}This checks structure, not whether a price or SKU is valid. Record numbers can differ from physical line numbers when quoted fields contain line breaks.
For existing iterator implementations, review runtime compatibility: the current SplFileObject::setCsvControl() documentation marks that method deprecated as of PHP 8.6. For new work, the explicit fgetcsv() loop above is a straightforward option.
Use League CSV when files come from outside your team
I would usually evaluate League CSV first for recurring supplier files and customer uploads. Its header mapping and encoding facilities provide useful building blocks:
composer require league/csvWith a current 9.x installation:
use League\Csv\Reader;
$csv = Reader::from('/path/to/import.csv', 'r');
$csv->setDelimiter(',');
$csv->setEscape('');
$csv->setHeaderOffset(0);
foreach ($csv->getRecords() as $offset => $record) {
// Validate mapped values before staging them.
}One behaviour deserves attention during review. As the Reader documentation explains, header mapping pads missing fields with null and truncates extra fields. Duplicate headings trigger an exception when used. If malformed row widths must cause rejection, validate raw records in a separate pass without header mapping first.
Reader skips an input BOM by default, but removing that marker does not convert the character encoding. Configure conversion for the known source encoding using the documented encoding facilities. Preview headings and sample values before approving an unfamiliar format, then save the confirmed supplier settings.
Where ParseCsv makes sense
ParseCsv offers automatic delimiter detection and character encoding conversion:
composer require parsecsv/php-parsecsvThat can be useful in an existing integration or when exploring unfamiliar files. Treat detection as a suggested setting for confirmation. A plausible preview is still worth checking against expected headings and values.
The official README explicitly confirms compatibility through PHP 8.3. That does not prove incompatibility with newer versions; it means your team should test the actual runtime and file samples before committing to it.
Make failures manageable for the person running the import
A useful importer needs a clear path from upload to recovery:
- Validate and stage first. Show proposed creates, updates, skips and rejections before applying live changes.
- Report actionable errors. Include the record, field, expected format and commit status. For example: “Record 18, price: expected a decimal such as 12.50. No changes applied.” Only use that last sentence when it is true.
- Design safe retries. Use stable business keys and record completed batches. Where possible, commit each batch and its progress marker together so an interruption cannot leave progress ambiguous.
- Keep processing bounded. Avoid collecting every parsed record in memory. Large jobs may need background processing, progress reporting and defined restart behaviour.
- Hand over recovery instructions. Name an owner and test duplicate records, extra columns, encoding differences and interrupted jobs.
If imports regularly require spreadsheet repairs or developer intervention, start with one troublesome file and trace its journey into the system. I can help review the workflow, agree on acceptance criteria and coordinate the implementation, so your team has a process it can operate and recover with confidence.
Related on GrN.dk
- Browser Automation for Operations and Agency Teams: What Should You Automate?
- GitHub Copilot Repo-Level Metrics: What Should Teams Measure?
- Give an AI Agent Its First Job on a Simple Task Board
Need help with this kind of work?
Review your CSV import workflow with Greg Get in touch with Greg.