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

标签 php mysql xml fwrite

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

因此将 open 移到循环之外。

第二个问题是您根本没有编写 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 文件,您需要根据需要设置元素名称。

关于php - 尝试从 mysql 查询写入 Php fwrite XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52630810/

相关文章:

PHP Mysql实时消息?

php - 具有大小写类名的自动装带器

php - 不允许更新 php 中的空文本框

php - 使用复选框将数据从 html 表单存储到 MySQL 数据库

php - 如何使用 PHP 和 MYSQL 通过条件嵌套创建 XML

xml - XSD 中的动态枚举

javascript - 带有确认对话框的功能

JavaScript ActiveXObject 未在浏览器控制台中定义

php - 如何使用 PHP 和 MySQL 对评论进行编号

xml - 无法转义用于 xml 构造的 html 字符串