PHP: Undefined index even if it exists

后端 未结 6 776
难免孤独
难免孤独 2021-01-18 03:22

It drives me crazy ... I try to parse a csv file and there is a very strange behavior.

Here is the csv

action;id;nom;sites;heures;jours
i;;\"un nom a         


        
6条回答
  •  逝去的感伤
    2021-01-18 03:48

    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.

提交回复
热议问题