Q:

How do I read a UTF CSV file in PHP with a BOM?

I have this code to read a CSV file.
$csv = array_map('str_getcsv', file($file));
var_dump($csv[0][0]).PHP_EOL;
...
echo $a['Type'];exit;

However when I try to use the first row of header columns for keys to an array of arrays, I get an error because the first column 'Type' also include the BOM. The BOM is being included in the file contents, and then included in the array key. See, it thinks the string 'Type' is 7 characters instead of 4, because it is including the BOM <U+FEFF>.

string(7) "Type" 
  PHP Notice 'yii\base\ErrorException' with message 'Undefined index: Type'

The file() function doesn't have an option for UTF. How do I use file() to read a UTF file?

A:

I'd personally avoid file, since it reads the entire file into memory. But assuming you're good with that, filter the BOM out manually:
$lines = file($file);
$lines[0] = preg_replace(sprintf('/^%s/', pack('H*','EFBBBF')), $lines[0]);
$csv = array_map('str_getcsv', $lines);

Untested, this is the alternative I'd use:
$fp = fopen($file, 'r');
fseek($fp, 3);
while ($line = fgetcsv($fp)) {
    $csv[] = $line;
}
fclose($fp);

If the BOM might not be present, then you'd need to beef up this algorithm.

