2013-03-16 6 views
1

$ _GET-data를 입력으로 받아서 csv 파일에 저장하는 PHP 코드를 작성하려고합니다. 내 CSV 파일 번 이상 코드를 실행하는 경우 은 다음과 같습니다php file() 함수가 따옴표와 쉼표를 만듭니다.

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

이 보인다. 보시다시피 첫 번째 줄에는 아무런 문제가 없습니다. 두 번째 줄 뒤에 인용문을 넣기 시작합니다. – mavili

답변

0

$ 된 FileContents 문자열의 배열로 읽어, CSV 파일의 라인하지만 실제 CSV 데이터 당 하나 개의 항목이 분석되지 않습니다. 마지막 fputcsv는이 데이터를 CSV로 쓰려고 시도하고 이스케이프 처리합니다 (따옴표 포함). 당신은 fwrite 대신 fputcsv 사용하여 파일을 이전 파일의 내용 ($ 된 FileContents)를 추가해야합니다 : 당신이 코드의 논리와 몇 가지 문제를 가지고있는 것처럼

fwrite($file, implode("\n", $fileContents)); 
+0

또한'$ fileContents = file ("weather_data.csv", FILE_IGNORE_NEW_LINES);를 사용하여 파일에 빈 줄을 추가하지 않습니다. – Smuuf

+0

좋은 지적! 또는'implode'을'implode ($ fileContents)'로 변경하십시오. – wldsvc