2013-05-14 49 views
3

我有PHP爲自己創建一個CSV文件,但是我正在查看是否有可能在文件創建時創建帶有標題(經度和緯度)的行,但不會在隨後的文件更新中創建。將行標題添加到使用PHP創建的csv?

<?php 
    $myFile = "locationlog"; 
    $fh = fopen($myFile, 'a') or die("can't open file"); 
    fwrite($fh, "\r\n"); 
    fwrite($fh, str_replace(array('lat=', '&lon='), array('', ','), file_get_contents('php://input'))); 
    fclose($fh); 
    echo "<html><head /><body><iframe src=\"$myFile\" style=\"height:100%; width:100%;\"></iframe></body></html>" 

?> 

此代碼創建一個這樣的文件:

55.0203786,-7.1819549 
55.0204016,-7.1819482 
55.0204016,-7.1819482 
55.0203927,-7.1819593 
55.0203927,-7.1819593 

,但我在尋找它來創建這樣一個文件:

Latitude,Longitude 
55.0203786,-7.1819549 
55.0204016,-7.1819482 
55.0204016,-7.1819482 
55.0203927,-7.1819593 
55.0203927,-7.1819593 

我手動試着把標題,但它似乎阻止PHP腳本再次更新文件。

編輯:

我一直在使用文件大小的方法嘗試。

<?php 
    $myFile = "locationlog"; 
    $fh = fopen($myFile, 'a') or die("can't open file"); 
    fwrite($fh, "\r\n"); 
    if(filesize($file) == 0) { fwrite($fh, "Latitude,Longitude\r\n"); } 
    elseif(filesize($file) > 0){ 
     fwrite($fh, str_replace(array('lat=', '&lon='), array('', ','), file_get_contents('php://input'))); 
    } 
    fclose($fh); 
    echo "<html><head /><body><iframe src=\"$myFile\" style=\"height:100%; width:100%;\"></iframe></body></html>" 

?> 

它似乎產生相反的效果,這顯示作爲結果:

Latitude,Longitude 

Latitude,Longitude 

Latitude,Longitude 

Latitude,Longitude 

我明明做錯事。

編輯2:

我想通了最後。謝謝您的幫助!這是腳本,以防將來任何人需要它。

<?php 
    $myFile = "locationlog"; 
    if(filesize(locationlog) == 0) { 
    $fh = fopen($myFile, 'a') or die("can't open file"); 
    fwrite($fh, "Latitude,Longitude"); 
    } 
    $fh = fopen($myFile, 'a') or die("can't open file"); 
    fwrite($fh, "\r\n"); 
    fwrite($fh, str_replace(array('lat=', '&lon='), array('', ','), file_get_contents('php://input'))); 
    fclose($fh); 
    echo "<html><head /><body><iframe src=\"$myFile\" style=\"height:100%; width:100%;\"></iframe></body></html>" 

?> 
+0

確保正確設置文件的方式,使PHP的過程可以編輯該文件。由於創建自己的文件來放置初始標題,所有者將會有所不同。 – Orbling

+5

值得一提[fputcsv](http://php.net/manual/en/function.fputcsv.php)? – ficuscr

+1

您可以在嘗試打開它進行追加前檢查文件是否存在,如果沒有則添加標頭。或者像你一樣打開它並檢查文件的位置。例如。 'if(ftell($ myFile)== 0){fwrite($ fh,「Latitude,Longitude \ r \ n」); }' – Orbling

回答

1

fwrite($fh, "\r\n"); 

之後添加

fwrite($fh, "Latitude,Longitude\r\n"); 
+0

每次都會添加它。 – Orbling

+0

用戶提到'在文件創建時創建一個帶有標題(經度和緯度)的行,但不在隨後的文件更新中「。使用[file_exists](http://php.net/manual/en/function.file-exists.php)檢查更新您的答案。 –

相關問題