$fp, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 600, CURLOPT_USERAGENT => 'ecoles-import/1.0', ]); $ok = curl_exec($ch); $err = curl_error($ch); curl_close($ch); fclose($fp); if (!$ok) { throw new RuntimeException("Téléchargement échoué ($dataset) : $err"); } } try { $pdo = db(); $pdo->exec( 'CREATE TABLE IF NOT EXISTS effectifs ( uai VARCHAR(12) NOT NULL, annee SMALLINT NOT NULL, eleves INT NOT NULL DEFAULT 0, classes INT NOT NULL DEFAULT 0, PRIMARY KEY (uai, annee), INDEX idx_uai (uai) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4' ); $tmpDir = __DIR__ . '/data/insee'; @mkdir($tmpDir, 0777, true); // Accumulateur uai → annee → élèves (somme GT+PRO pour les polyvalents). $acc = []; foreach (SOURCES as [$ds, $uaiCol, $popCol]) { $csv = "$tmpDir/$ds.csv"; say("… Téléchargement $ds …"); download_csv($ds, $uaiCol, $popCol, $csv); $fh = fopen($csv, 'r'); $header = fgetcsv($fh, 0, ';'); $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string) $header[0]); $iY = array_search('rentree_scolaire', $header, true); $iU = array_search($uaiCol, $header, true); $iE = array_search($popCol, $header, true); if (in_array(false, [$iY, $iU, $iE], true)) { throw new RuntimeException("Colonnes introuvables dans $ds."); } $rows = 0; while (($r = fgetcsv($fh, 0, ';')) !== false) { $uai = $r[$iU] ?? ''; $annee = (int) substr((string) ($r[$iY] ?? ''), 0, 4); if ($uai === '' || $annee === 0) { continue; } $eleves = (int) round((float) str_replace(',', '.', (string) ($r[$iE] ?? '0'))); $acc[$uai][$annee] = ($acc[$uai][$annee] ?? 0) + $eleves; $rows++; } fclose($fh); @unlink($csv); say(" $ds : $rows lignes."); } $ins = $pdo->prepare('REPLACE INTO effectifs (uai, annee, eleves, classes) VALUES (?, ?, ?, 0)'); $pdo->beginTransaction(); $n = 0; foreach ($acc as $uai => $byYear) { foreach ($byYear as $annee => $eleves) { $ins->execute([$uai, $annee, $eleves]); if (++$n % 5000 === 0) { $pdo->commit(); $pdo->beginTransaction(); } } } $pdo->commit(); say("✔ Effectifs 2nd degré : $n lignes (collèges + lycées) importées."); say('🎉 Terminé.'); } catch (Throwable $e) { if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); } http_response_code(500); say('!! ERREUR : ' . $e->getMessage()); exit(1); }