尝试从 mysql 查询写入 Php fwrite XML 文件

Trying to write Php fwrite XML file from mysql query

我正在尝试编写一些代码来获取 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

我完全被这个弄糊涂了。如果这是我看过的基本内容,请原谅我并提前致谢。

问题是你在每次循环中打开文件,这会覆盖以前的数据...

   $myfile = fopen("test.xml", "w") or die("Unable to open file!");
   while($row = $result->fetch_assoc()) {

所以把开路移到循环外。

第二个问题是您根本没有写 XML。你需要做类似...

$xml = simplexml_load_string("<coords />");

while($row = $result->fetch_assoc()) {
    $newCoord = $xml->addChild("coord");
    $newCoord->addChild("latitude", $row["latitude"]);
    $newCoord->addChild("longitude", $row["longitude"]);
}
$xml->saveXML("test.xml");

这将生成一个简单的 XML 文件,您需要根据需要设置元素名称。

首先将连接放在 foreach 循环之外,将 fopen 放在 while 循环之外 环形。

根据文档

,您以 'w' 模式打开 xml 文件

Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

您需要追加模式'a'

Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.

这对你有用。但是您仍然根据邮政编码发出数据库请求,我建议收集您需要查询的所有邮政编码,并使用 sql IN 运算符向数据库发出一个数据库请求。