exec( 'CREATE TABLE IF NOT EXISTS iris_pop ( code VARCHAR(12) NOT NULL PRIMARY KEY, com VARCHAR(5) NOT NULL, pop DOUBLE NOT NULL DEFAULT 0, INDEX idx_com (com) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4' ); $csv = __DIR__ . '/data/insee/base-ic-evol-struct-pop-2022.CSV'; if (!is_file($csv)) { throw new RuntimeException( "Fichier absent : $csv\n" . " Téléchargez et dézippez la base IRIS dans data/insee/ (voir l'en-tête de ce script)." ); } $fh = fopen($csv, 'r'); $header = fgetcsv($fh, 0, ';'); $iIris = array_search('IRIS', $header, true); $iCom = array_search('COM', $header, true); $iPop = array_search('P22_POP', $header, true); if ($iIris === false || $iCom === false || $iPop === false) { throw new RuntimeException('Colonnes IRIS / COM / P22_POP introuvables.'); } $ins = $pdo->prepare('REPLACE INTO iris_pop (code, com, pop) VALUES (?, ?, ?)'); $pdo->beginTransaction(); $n = 0; while (($row = fgetcsv($fh, 0, ';')) !== false) { $code = $row[$iIris] ?? ''; if ($code === '') { continue; } $com = $row[$iCom] ?? substr($code, 0, 5); $pop = (float) str_replace(',', '.', (string) ($row[$iPop] ?? '0')); $ins->execute([$code, $com, $pop]); if (++$n % 5000 === 0) { $pdo->commit(); $pdo->beginTransaction(); } } $pdo->commit(); fclose($fh); say("✔ iris_pop : $n IRIS importés (population 2022)."); say('🎉 Terminé.'); } catch (Throwable $e) { if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); } http_response_code(500); say('!! ERREUR : ' . $e->getMessage()); exit(1); }