PHP: Undefined index even if it exists

I had the same problem with CSV files generated in MS Excel using UTF-8 encoding. Adding the following code to where you read the CSV solves the issue:

$handle = fopen($file, 'r');

// ...

$bom = pack('CCC', 0xef, 0xbb, 0xbf);

if (0 !== strcmp(fread($handle, 3), $bom)) {
    fseek($handle, 0);
}
// ...

What it does, is checking for the presence of UTF-8 byte order mark. If there is one, we move the pointer past BOM. This is not a generic solution since there are other types BOMs, but you can adjust it as needed.


If your CSV file is in UTF-8 encoding,

make sure that it's UTF-8 and not UTF-8-BOM.

(you can check that in Notepad++, Encoding menu)


Probably there is some special character at the beginning of the first line and trim isn't removing it.

Try to remove every non-word character this way:

// Identify headers
if(!isset($headers))
{
    for($i=0;$i<$cols;$i++)
    {
        $headers[preg_replace("/[^\w\d]/","",strtolower($row[$i]))] = $i;
....

Tags:

Php