将HTML表单字段创建为数组

时间:2016-06-16 13:39:52

标签: php arrays fputcsv

16君16

您好, 我有一个带有文本,单选按钮,复选框和文本区域字段的HTML表单。我想将所有字段写入CSV文件。它正在写入CSV文件,但不幸的是,如果任何字段中都有逗号,它会将逗号后的文本移动到下一个字段。

我做了一些研究,发现我应该使用' fputcsv'。我找到的所有示例都是从数据库中获取数据并创建数组。我想知道如何从我的表单中的数据创建一个数组,以便我可以使用' fputcsv'。以下是我的代码示例。

// 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 \n";

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

请尽可能详细地说明您的答案。

提前感谢您的时间和考虑。

2 个答案:

答案 0 :(得分:0)

PHP:那是

的功能

http://php.net/manual/en/function.fputcsv.php

编辑:复制PHP文档:

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

以上示例将以下内容写入file.csv:

  

AAA,BBB,CCC,DDDD
  123,456,789
  &#34;&#34;&#34; AAA&#34;&#34;&#34;&#34;&#34;&#34; BBB&#34;&#34;&#34;

答案 1 :(得分:0)

如果使用fputcsv,则已存在默认转义字符(“\”) 所以你要做的就是从表单输入中创建一个数组并将它们写入文件。

// 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);

在这个例子中,我也将标题写入文件,但是如果你使用的是fopen(...,“a”);这可能没有意义所以你可能想要使用“w”作为参数(如果你想在文件中存储超过1行的话,那就不行了。然后在每一行之前不要写标题)

希望这有所帮助,欢呼