If the first CSV header looks like sku but PHP refuses to find that key, check the first three bytes of the file. A UTF-8 byte order mark, or BOM, starts with EF BB BF. Some exporters put those bytes before the first header. Skip them before calling fgetcsv(), then validate the parsed header as you normally would.
The position matters. Removing the prefix from a parsed field can appear to work with an unquoted header and still leave you with a problem when the exporter quotes the first field. Checking the file stream first gives the CSV parser the same starting point whether the file was saved with a BOM or without one. This guide uses PHP 8 and a local comma-separated file.
1. Confirm which part of the import failed
Start with the smallest failing file you can make. Use an artificial header such as sku,price and one data row such as A12,4.50. Keep a copy of the original export, because opening and saving it in another editor can change the encoding or remove the exact bytes you need to diagnose. If the import normally contains customer data, use the small local fixture for debugging instead of copying real rows into logs.
Check whether only the first header is affected. If the parser returns the expected number of fields and the second field matches exactly, a prefix on the first header is plausible. If the whole header appears in a single field, check the separator. An exporter may use a semicolon or tab, and dropping three bytes from that file will not make the separator match your parser settings.
Compare values exactly. The string you see printed on screen can hide characters. On a local test file, use bin2hex() on the first field to reveal its bytes. For an unquoted SKU header, the ordinary ASCII letters appear as 736b75. With a UTF-8 BOM attached to the same field, you may see efbbbf736b75. The extra characters are then a property of the string, even if your terminal draws only the letters.
Look at the file itself as well. If the exporter quotes the first cell, the BOM sits before the opening quotation mark. That can change how the parser interprets that first field. A hex check on the stream catches the prefix regardless of whether the header begins with a quote.
2. Inspect the prefix without changing the file
Open the file in binary read mode. Read the first three bytes and compare them with the exact UTF-8 BOM. When they match, the stream is already positioned at the first real content byte. When they do not match, rewind to the beginning. That second branch is important because otherwise an ordinary file would lose its first three bytes, including the entire word sku in this example.
A BOM is useful evidence about the start of the file. It does not by itself prove that the rest of the data is valid UTF-8. If the header matches after skipping it but names or product descriptions are still garbled, diagnose the file's encoding separately. For example, a UTF-16 file needs conversion to an encoding your import supports before you parse the rows. That is a different job from stripping a UTF-8 prefix.
Apply the check once, at offset zero on the stream. Running a global replacement over every field can alter bytes that were intended as content. If you see a suspicious character later in the file, investigate where it came from. Keep the prefix check narrow enough that the original cell values can still be used to diagnose the problem.
3. Skip the prefix before reading the CSV header
Save the example below as read-header.php next to your test file. It accepts a path from the command line and defaults to sample.csv. It checks only the first three bytes, rewinds when needed, parses the header and validates the two expected column names in order. It closes the file even if a check fails.
<?php
$path = $argv[1] ?? __DIR__ . '/sample.csv';
$stream = fopen($path, 'rb');
if ($stream === false) {
throw new RuntimeException('Could not open the CSV file.');
}
try {
$prefix = fread($stream, 3);
if ($prefix === false) {
throw new RuntimeException('Could not read the CSV prefix.');
}
if ($prefix !== "\xEF\xBB\xBF" && !rewind($stream)) {
throw new RuntimeException('Could not rewind the CSV file.');
}
$header = fgetcsv($stream, 0, ',', '"', '');
if ($header !== ['sku', 'price']) {
throw new RuntimeException('Expected CSV columns: sku, price.');
}
echo "Header matched.\n";
} finally {
fclose($stream);
}
Run it with php read-header.php sample.csv. The example uses a local, seekable file. If you are processing a non-seekable source, such as a pipe, use an approach that preserves the bytes you read when the prefix does not match. A temporary seekable stream is one option when the input is small enough for the way you plan to store it.
Notice the explicit empty escape argument in fgetcsv(). From PHP 8.4, relying on its default escape value is deprecated. The empty string disables PHP's proprietary escape mechanism while standard doubled quotes remain available. Check the actual export format if an upstream tool uses a different dialect. The PHP fgetcsv manual explains the separator, enclosure and escape arguments.
4. Try both quoted and unquoted fixtures
Make two identical plain UTF-8 files containing the header and one row. Leave one file without a BOM. Save the second with a UTF-8 BOM if your editor offers that option. If the tool only offers something called Unicode, check the actual bytes before using the file as a test. That label can refer to more than one encoding.
Test each file with the same PHP command, changing only the filename. Both should print the same success message. Next, repeat with a header that has quotes around both column names. This covers the case where the parser needs to see an opening quote as the first byte of the CSV record. The expected parsed values stay the same in all four cases.
Keep an empty file and a file with an unexpected header as negative cases. The example should reject both because neither contains the exact two fields. Also try a UTF-8 file whose first column really is called something else. Skipping a BOM should never make a wrong set of column names acceptable. Separating parsing from validation makes that distinction easy to test.
If the production importer subsequently reads rows from the same stream, keep that work inside the same try block. The first fgetcsv() call consumes the header record, leaving the stream ready for the next one. Reopening the file for the row loop can put you back at the prefix and header, so check how the existing importer passes the stream between steps.
5. Validate the header before mapping rows
Choose whether your application expects a fixed column order. In the example, price,sku is rejected even though it has the same names. That is deliberate for a format that promises a fixed order. If your import contract allows arbitrary order, validate that the required names are present exactly once and build a map from name to index.
Check for duplicate names before using the strings as array keys. If a source file contains two columns called price, the mapping is ambiguous. Reject it with a useful error rather than guessing which one the exporter meant. File headers are a good place to fail early because row-level errors can otherwise make a simple format problem look like dozens of unrelated data problems.
Check field counts as you read data records. A blank record, a missing price and a quoted comma in a description are different cases. Let the CSV parser handle quoting, then decide what your application does with missing or blank values. Splitting the raw row on a comma would lose the distinction between a separator and a comma inside a quoted field.
If you intentionally allow variations such as capital letters or surrounding spaces, document that behaviour and apply it consistently. Do not add a broad trim or case conversion merely because the first file failed. A tighter rule is easier to debug when two upstream exporters use slightly different headings. Use the BOM check to deal with the bytes at the beginning, then use the schema rules you agreed with the source.
6. Work through failures that look similar
The first field starts with a quote. Inspect the first bytes of the file and verify the delimiter and enclosure passed to PHP. Check that the code skips the BOM before calling the parser and that the file has not already been partly read elsewhere. Try the quoted fixture to reproduce the failure independently of the original export.
Every field is in one string. Check the separator in the file. A semicolon-separated export needs a semicolon in the parser call. Run the same test against a short fixture using that separator. A BOM can coexist with the wrong separator, so fixing one can make the other easier to see.
The first ordinary file loses letters. Make sure the rewind happens when the bytes do not match. If the file is shorter than three bytes, the read can return a shorter string. That also takes the rewind branch. Check that a file with no prefix still has the correct header before handling real imports.
Only certain accented letters look wrong. Verify the export encoding before changing parsing rules. Open a fixture in a tool that reports the encoding or inspect a known character's bytes. A check for a UTF-8 BOM has no effect on code-page differences further inside the file. Once decoding is correct, run the same header and row checks again.
7. Keep the importer and the example easy to verify
Save the four small positive fixtures and the negative ones alongside your import tests. Name them for the condition each exercises. When you change the PHP version or replace a spreadsheet exporter, run the fixtures before testing a large file. They isolate quoting, prefix handling and schema errors without depending on whatever the latest production export happens to contain.
If you publish your own guide about the fix, check that the code sample shows the actual opening PHP tag and backslashes when copied. Content editors can interpret angle brackets instead of displaying them. The HTML details guide has another example of checking that markup survives as copyable text. In the importer itself, keep the file open, BOM check, parser call and header validation in that order so the next person can follow the stream position.
8. Make the error useful for the next import
In a production importer, report the expected column names and which validation rule failed. A message that says the file has one field where two were expected sends you to the delimiter first. A message that says the first header differs sends you to the bytes and the spelling. Keep the explanation short enough that somebody preparing a new export can act on it without reading the PHP source.
Record the source application and export settings alongside your fixtures if you control the upstream process. Those details help when someone replaces the original spreadsheet template or changes the export locale. A new export with a different delimiter should be treated as a format change, even if it has the same filename.
Before handing the importer back to others, run one representative file through the normal workflow and check that the first data row is still there. Passing a header test establishes that the stream reaches the parser at the right position. Checking the first row separately catches mistakes introduced when the rest of the import loop was connected.
