doutang2017 2018-04-14 11:16
浏览 66
已采纳

通过PHP将标头添加到CSV文件

I have the following PHP script for creating CSV and collecting data from HTML form to CSV file, but I can't add headers to the first row of CSV file. I'm a newbie in PHP world so I'll appreciate if anyone can use this code to help me with that:

<?php

$fieldA = $_POST["prezime"];
$fieldB = $_POST["ime"];
$fieldC = $_POST["datumrodjenja"];
$fieldD = $_POST["mestorodjenja"];
$fieldE = $_POST["rod"];
$fieldF = $_POST["prebivaliste"];
$fieldG = $_POST["brojpasosa"];
$fieldH = $_POST["izdatod"];
$fieldI = $_POST["vazido"];
$fieldJ = $_POST["profesija"];
$fieldK = $_POST["zanimanje"];
$fieldL = $_POST["fiksni"];
$fieldM = $_POST["mobilni"];
$fieldN = $_POST["email"];
$fieldO = $_POST["napomena"];

$keys = array($fieldA,$fieldB,$fieldC,$fieldD,$fieldE,$fieldF,$fieldG,$fieldH,$fieldI,$fieldJ,$fieldK,$fieldL,$fieldM,$fieldN,$fieldO); //THIS IS WHERE YOU PUT THE FORM ELEMENTS ex: array('$fieldA','$fieldB',etc)

$fname = 'prijave.csv';
$fp = fopen($fname,'a');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

fputcsv($fp, $keys);
fclose($fp);

?>
  • 写回答

2条回答 默认 最新

  • dongzhi6905 2018-04-14 11:21
    关注

    You could create a array with your keys, and create a loop to get values. Then use fputcsv() to write header and values:

    $keys = ["prezime", "ime", "datumrodjenja", "mestorodjenja", "rod", "prebivaliste",
             "brojpasosa", "izdatod", "vazido", "profesija", "zanimanje", "fiksni", "mobilni",
             "email", "napomena"];
    
    $values = [];
    foreach ($keys as $key)
        $values[] = $_POST[$key];
    
    $fname = 'prijave.csv';
    $fp = fopen($fname,'a');
    //add BOM to fix UTF-8 in Excel
    fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
    fputcsv($fp, $keys);
    fputcsv($fp, $values);
    fclose($fp);
    

    Edit: To add values but not BOM and headers each time, you could check if the file exists, and add them only if the file is new:

    // same code as above ($header + $values)
    // then,
    $fname = 'prijave.csv';
    if (!file_exists($fname)) {
        $fp = fopen($fname,'a');
        //add BOM to fix UTF-8 in Excel
        fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
        fputcsv($fp, $keys);
    }
    else {
        $fp = fopen($fname,'a');
    }
    fputcsv($fp, $values);
    fclose($fp);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥66 定制开发肯德基自动化网站下单软件
  • ¥20 vscode虚拟环境依赖包未安装
  • ¥15 odoo17关于owl开发js代码问题
  • ¥15 光纤中多普勒频移公式的推导
  • ¥15 怎么制作一个人脸识别门禁系统
  • ¥20 大华dss监控平台网络关闭登不进去
  • ¥15 请使用蚁群算法解决下列问题,并给出我完整的代码
  • ¥20 关于php录入完成后,批量更新数据库
  • ¥15 请教往复密封润滑问题
  • ¥15 cocos creator发布ios包