【发布时间】:2023-06-02 05:16:02
【问题描述】:
我正在尝试编写一些代码来获取 CSV 文件,然后提取相关的邮政编码列,然后在具有经度和纬度字段的 MySql 数据库中查找该邮政编码,然后将它们保存到 XML 文件中,以便可以在不同的地方使用程序
我认为这段代码可以正常工作,但由于某种原因,它只输出查询的最后一个字段:
//Open the file.
$fileHandle = fopen("test.csv", "r");
$postcode = array();
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
array_push($postcode, $row[40]);
}
$postcodefil = (array_unique($postcode));
$postcodefil = str_replace(' ', '', $postcodefil);
$postcodefil = preg_replace('/\s+/', '', $postcodefil);
//print_r($postcodefil);
foreach ($postcodefil as $value) {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT postcode, latitude, longitude FROM postcode WHERE postcode='$value' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myfile = fopen("test.xml", "w") or die("Unable to open file!");
$lat = $row["latitude"];
$lng = $row["longitude"];
fwrite($myfile, $lat."testss".$lng."\n");
echo $lat;
echo $lng;
echo "<br />";
}}
} // end of foreach
$conn->close();
但是当我运行它时,它会正确地回显
50.822398-0.139938
51.444908-1.295341
50.841951-0.842508
51.308504-0.551835
etc.... etc...
但 Fwrite 只输出最后一行
51.120916testss-0.599545
我对此完全感到困惑。如果这是我看过的基本内容,请原谅我并提前感谢。
【问题讨论】: