如何使用PHP从html表单导出到csv文件

时间:2017-12-07 22:57:33

标签: php csv post fputcsv

尝试#1:

$title = $_POST['title'];
$email = $_POST['email'];
$description = $_POST['description'];
$type = $_POST['type'];
$content = $_POST['content2'];

$fs = fopen("blogPosts.csv", "a");
fputcsv($fs, array($title,$email,$description,$type,$content2,));
fclose($fs);

尝试#2:

$title = $_POST['title'];
$email = $_POST['email'];
$description = $_POST['description'];
$type = $_POST['type'];
$content = $_POST['content2'];

$list = array (
    array($title, $email, $description, $type, $content)
);
$fileName = "blogPosts.csv";

function generateCsv(array $list, $fileName,  $delimiter = ',', $enclosure = '"') {
    $handle = fopen($fileName, 'r+');
    foreach ($list as $line) {
        fputcsv($handle, $line, $delimiter, $enclosure);
    }
    rewind($handle);
    $contents = '';
    while (!feof($handle)) {
        $contents .= fread($handle, 8192);
    }
    fclose($handle);
    return $contents;
}

generateCsv($list, 'blogPosts.csv');

这是我使用PHP附加到csv文件时的两次尝试。第一个目前不起作用。第二行写入第二行,但会覆盖删除前一条记录的第一行。

我每次都需要将5个变量插入到新行中。

0 个答案:

没有答案