2012-05-18 70 views
1

我有這種格式的國家的細節.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

你正在使用哪個'RDBMS'? – Quassnoi

+0

你只需要讀取文件,將每一行分割爲bei commata,創建INSERT語句... done(?) – djot

回答

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. 
    } 
} 
+0

是否可以插入3個獨立的表格,如國家州市 – Natasha

+0

當然,請記住,您的數據設置是針對城市的,因此如果您每次只插入第一列,就會出現重複的國家/地區。編輯您的問題以包含您的表格定義,我可以更新答案以向您展示如何做到這一點。 – davidethell

+0

我只需要菲律賓的州和城市,例如$ data [0] = ph – Natasha

0

如果你的數據庫是MySQL的,存在一個工具來批量插入,documentation

如果沒有,可能是你的數據庫也有一個,但如果你想用PHP來做這件事,@ davidethell的例子很適合做任務

相關問題