我有一个 .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文件读取数据并将其插入数据库的任何可能方法吗?
如何获取州和城市数据库?
答案 0 :(得分:2)
以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.
}
}
答案 1 :(得分:0)
如果您的数据库是mysql,则存在一个批量插入的实用程序documentation
如果没有,可能你的数据库也有一个,但是如果你想用PHP做这个,@ davidethell的例子很适合做任务