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 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?