获取文件的详细信息,然后插入到数据库


get details on file then insert to database

我有一个.txt文件,其中包含以下格式的所有国家/地区的详细信息:

Country,City,AccentCity,Region,Population,Latitude,Longitude
ad,aixas,Aixàs,06,,42.4833333,1.4666667
ad,aixirivali,Aixirivali,06,,42.4666667,1.5
ad,aixirivall,Aixirivall,06,,42.4666667,1.5
ad,aixirvall,Aixirvall,06,,42.4666667,1.5
ad,aixovall,Aixovall,06,,42.4666667,1.4833333
ad,andorra,Andorra,07,,42.5,1.5166667
ad,andorra la vella,Andorra la Vella,07,20430,42.5,1.5166667
ad,andorra-vieille,Andorra-Vieille,07,,42.5,1.5166667
ad,andorre,Andorre,07,,42.5,1.5166667
ad,andorre-la-vieille,Andorre-la-Vieille,07,,42.5,1.5166667
ad,andorre-vieille,Andorre-Vieille,07,,42.5,1.5166667
ad,ansalonga,Ansalonga,04,,42.5666667,1.5166667

我必须将这些数据插入 3 个表中,例如城市、州和国家/地区,而不会重复。

有什么可能的方法可以从.txt文件中读取数据并将其插入数据库?

如何获取州和城市数据库?

将文件读取为 CSV 格式,然后插入:

if (($handle = fopen("cities.txt", "r")) !== FALSE) {
    while (($data = fgetcsv($handle)) !== FALSE) {
        // Craft your SQL insert statement such as:
        $sql = "INSERT INTO cities (country, city, accent_city, etc.) VALUES ('{$data[0]}','{$data[1]}','{$data[2]}', etc.)";
        // Use the appropriate backend functions depending on your DB, mysql, postgres, etc.
    }
}

如果你的数据库是mysql,存在一个实用程序来批量插入,文档

如果没有,可能你的数据库也有一个,但如果你想使用 PHP 来做到这一点,@davidethell的例子非常适合完成任务