我正在尝试编写一些PHP代码,它将$ _GET-data作为输入并将其保存到csv文件中。 当多次运行代码时,我的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);
?>
答案 0 :(得分:0)
$ fileContents读取为字符串数组,每行CSV文件一个条目,但不解析实际的CSV数据。最后一个fputcsv尝试将此数据写为CSV并将其转义(添加引号和内容)。您需要使用fwrite
而不是fputcsv
将旧文件内容($ fileContents)添加到您的文件中:
fwrite($file, implode("\n", $fileContents));