1

我正在尝试编写一些将 $_GET-data 作为输入并将其保存到 csv 文件中的 php 代码。多次运行代码时,我的 csv 文件如下所示:

Date,Time,Temperature,"Air Humidity","Soil Humidity",Light,"Wind Direction","Wind Speed",Rain
2013-03-16,16:24:27,12,80,40,82,255,10,0
"2013-03-16,16:24:26,12,80,40,82,255,10,0
","""2013-03-16,16:24:26,12,80,40,82,255,10,0
",""",""""""2013-03-16,16:24:25,12,80,40,82,255,10,0
",""","""""",""""
",""",""""""
","""
"

如您所见,该程序将引号和逗号添加到我不想要的数据中。这显然是由 'file("weather_data.csv")' 完成的,但我不知道如何禁用或解决此问题。

这是我现在的代码:

<?php

// Save received data into variables:
$temperature  = $_GET["t"];
$airHumidity  = $_GET["ha"];
$soilHumidity = $_GET["hs"];
$light        = $_GET["l"];
$windDir      = $_GET["wd"];
$windSpeed    = $_GET["ws"];
$rain         = $_GET["r"];

// Arrays for the column descriptor (first line in the csv-file) and the recent data:
$columnDescriptor = array("Date","Time","Temperature","Air Humidity","Soil Humidity","Light","Wind Direction","Wind Speed","Rain");
$recentData       = array(date("Y-m-d"),date("H:i:s"),$temperature,$airHumidity,$soilHumidity,$light,$windDir,$windSpeed,$rain);

$fileContents = file("weather_data.csv");
array_shift($fileContents); // removes first field of $fileContents

$file = fopen("weather_data.csv","w");

fputcsv($file,$columnDescriptor);
fputcsv($file,$recentData);
fputcsv($file,$fileContents);

fclose($file);

?>
4

1 回答 1

0

$fileContents 被读取为字符串数组,CSV 文件每行一个条目,但不解析实际的 CSV 数据。最后一个 fputcsv 尝试将此数据写入 CSV 并将其转义(添加引号和内容)。您需要将旧文件内容 ($fileContents) 添加到您的文件中,fwrite而不是fputcsv

fwrite($file, implode("\n", $fileContents));
于 2013-03-16T16:08:22.097 回答