douru5373 2013-05-14 20:30
浏览 140

在用PHP创建的csv中添加行标题?

I have PHP creating a CSV file for myself, however I'm looking to see if it's possible to create a row with titles (Latitude and longitude) on the files creation, but not in subsequent updates of the file.

    <?php
    $myFile = "locationlog";
    $fh = fopen($myFile, 'a') or die("can't open file");
    fwrite($fh, "
");
    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>"

?>

This code creates a file like this:

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

but I'm looking for it to create a file like this:

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

I've tried manually putting the titles in, but it seems to stop the PHP script from updating the file again.

EDIT:

I've tried using the filesize method.

<?php
    $myFile = "locationlog";
    $fh = fopen($myFile, 'a') or die("can't open file");
    fwrite($fh, "
");
    if(filesize($file) == 0) { fwrite($fh, "Latitude,Longitude
"); }
    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>"

?>

It seems to have the opposite effect, showing this as the result:

Latitude,Longitude

Latitude,Longitude

Latitude,Longitude

Latitude,Longitude

I'm obviously doing something wrong.

EDIT 2:

I figured it out eventually. Thanks for the help! Here's the script, in case anyone needs it in the future.

<?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, "
");
    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>"

?>
  • 写回答

1条回答 默认 最新

  • dongtangu8403 2013-05-14 20:34
    关注

    after

    fwrite($fh, "
    ");
    

    add

    fwrite($fh, "Latitude,Longitude
    ");
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?