duanfuchi7236 2016-06-16 13:39
浏览 20
已采纳

将HTML表单字段创建为数组

16-Jun-16

Hi, I have an HTML form with text, radio buttons, check boxes, and text area fields. I want to write all the fields into a CSV file. It is writing to the CSV file, but unfortunately if there is a comma in any of the fields, it moves the text after the comma to the next field.

I did some research and found I should use 'fputcsv'. All the examples that I found were getting their data from a database, and creating an array. I would like to know how to create an array from the data in my form so I can use it with 'fputcsv'. Below is a sample of my code.

// Create file. If file has been created, open file.
$myfile = fopen("ZZZmycsv.csv", "a") or die("Unable to open file!");

// Write to file.
// Column headers
$msg = "First Name, Last Name, Organization, Email, City, State, Comment 1, Comment 2 
";

// Form variables
$msg .= "$firstName, $lastName, $organization, $email, $city, $state, $comment1, $comment2 
";

Please be as detailed as possible with your answers.

Thanks in advance for your time and consideration.

  • 写回答

2条回答 默认 最新

  • doukan5332 2016-06-16 14:19
    关注

    If you use fputcsv, there is already a default escape character ("\") so all you have to do is make an array from the form inputs and write them into the file.

    // Create file. If file has been created, open file.
    $myfile = fopen("ZZZmycsv.csv", "a") or die("Unable to open file!");
    
    // Write to file.
    // Column headers
    $headers = array('First Name', 'Last Name', 'Organization', 'Email', 'City', 'State', 'Comment 1', 'Comment 2');
    fputcsv($myfile, $headers);
    
    // Form variables
    $formArray = array($firstName, $lastName, $organization, $email, $city, $state, $comment1, $comment2);
    fputcsv($myfile, $formArray);
    

    In this example i wrote the headers into the file too, but if you're using fopen(..., "a"); this will possibly make no sense so you may want to use "w" as parameter (not if you want to store more than 1 line in the file. then dont write headers before each line)

    hope this helped, cheers

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题