Question

I'm trying to write some php-code that takes $_GET-data as an input and saves it into a csv-file. When running the code more than once my csv-file looks like this:

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
",""","""""",""""
",""",""""""
","""
"

As you can see, the program adds quotation marks and commas into my data that I don't want. This is apparently done by 'file("weather_data.csv")' but I don't know how to disable or work around this.

This is my code for now:

<?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);

?>
Was it helpful?

Solution

$fileContents is read as an array of strings, one entry per line of the CSV file but the actual CSV data is not parsed. The last fputcsv tries to write this data as CSV and escapes it (adding quotes and stuff). You need to add the old file contents ($fileContents) to your file with fwrite instead of fputcsv:

fwrite($file, implode("\n", $fileContents));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top