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 48 49 50 51 52 53 54 55
| <?php
$fichier = 'test.csv';
$separateur = ';';
$table_temp = 'test_csv';
try
{
$dbh = new PDO('sqlite::memory:');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
catch(PDOException $e)
{
exit($e->getMessage());
}
$file = new SplFileObject($fichier);
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY);
$file->setCsvControl($separateur);
$entete_champs = $file->fgets();
$tab_champs = explode ($separateur,$entete_champs);
$champs_sqlite = implode(',',$tab_champs);
$champs_insert = array_fill(0,count($tab_champs),'?');
$champs_insert = implode(',',$champs_insert);
$dbh->exec("CREATE TABLE $table_temp ($champs_sqlite)");
$stmt = $dbh->prepare("INSERT INTO $table_temp VALUES ($champs_insert)");
foreach($file as $row)
{
if ($file->key() !== 0) $stmt->execute($row);
}
$query = $dbh->query("SELECT * FROM $table_temp");
echo '<table>';
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
?> |
Partager