3

我让 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>"

?>
4

1 回答 1

1

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

添加

fwrite($fh, "Latitude,Longitude\r\n");
于 2013-05-14T20:34:29.427 回答