1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| if (( ! is_file($filepath)) || (false === (self::$handle = fopen($filepath, 'r')))) {
throw new Exception("impossible to open the file '$filepath'");
}
if (isset(self::$handle)) {
$row = fgets(self::$handle);
$row=strtolower($row); //mettre header en minuscules
} // doit contenir les en-têtes des colonnes}
if (empty($row)) {
self::$errors[] = 'The file is empty';
return false;
}
// séparateur
if (mb_stripos($row, ',') !== false) {
self::$separator = ',';
} elseif (mb_stripos($row, ';') !== false) {
self::$separator = ';';
} else {
self::$errors[] = 'Unable to detect the CSV field separator';
return false;
}
$char = mb_substr($row, 0, 1); // premier caractère
if ($char === '\xef\xbb\xbf') { //if first character is BOM, one begins with the next character
$row = mb_substr($row, 1);
$char = mb_substr($row, 0, 1);
}
if (($char === '"') && (mb_stripos($row, '"'.self::$separator.'"') !== false)) {
self::$enclosure = '"';
} elseif (($char === "'") && (mb_stripos($row, "'".self::$separator."'") !== false)) {
self::$enclosure = "'";
}
if (self::$enclosure) {
// on vérifie que le premier séparateur trouvé est bien entouré de lettres ASCII
$i = mb_stripos($row, self::$separator);
if ($i) {
$fc = mb_substr($row, $i - 1, 1);
$lc = mb_substr($row, $i + 1, 1);
if (ctype_alpha($fc) && ctype_alpha($lc)) {
self::$enclosure = '';
}
}
}
else self::$enclosure = ''; |
Partager