1

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

?>
  • it looks like you have some issues with your logic of the code. as you can see, the first line has no problem, it starts to put quotations only after the second line. – mavili Mar 16 '13 at 15:46

1 Answers1

0

$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));
wldsvc
  • 1,242
  • 9
  • 13
  • Also use `$fileContents = file("weather_data.csv",FILE_IGNORE_NEW_LINES);` instead, so there won't be empty lines added to the file. – Smuuf Mar 16 '13 at 16:18
  • Good point ! Or change the `implode` to `implode($fileContents)` – wldsvc Mar 16 '13 at 16:39