我有PHP为我自己创建一个CSV文件,但是我想看看是否有可能在文件创建上创建具有标题(纬度和经度)的行,但不是在文件的后续更新中。
<?php
$myFile = "locationlog";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "rn");
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脚本再次更新文件。
编辑:我试过使用filesize方法。
<?php
$myFile = "locationlog";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "rn");
if(filesize($file) == 0) { fwrite($fh, "Latitude,Longitudern"); }
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, "rn");
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>"
?>
after
fwrite($fh, "rn");
添加fwrite($fh, "Latitude,Longitudern");