在PHP上打开,编辑和下载.csv文件的问题

时间:2014-05-07 09:18:01

标签: php csv file-io download

我想用PHP打开一个名为csv.csv的csv文件,然后在这个文件中添加新行,最后下载新闻csv。

csc.csv的内容是:

name, town
name1, town1
name2, town2
name3, town3
name4, town4 

我要添加这些行:

name5, town5
name6, town6

我制作了这个PHP代码,但它不起作用:

<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");


$file = fopen("csv.csv","r");
$list = array();
while(! feof($file))
  {
  $list[] = array(print_r(fgetcsv($file)));
  }
fclose($file);

$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');

outputCSV($list);

function outputCSV($list) {
    $output = fopen("php://output", "w");
    foreach ($list as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
}
?>

1 个答案:

答案 0 :(得分:0)

这是您的工作代码。

<?php

$file = fopen("csv.csv","a+");

$list = array();
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');

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

fclose($file);

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=csv_".time().".csv");
header("Pragma: no-cache");
header("Expires: 0");
?>

更新1:

用于创建新文件而不编辑现有文件。

<?php 
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");


$file = fopen("csv.csv","r");
$list = array();

while(! feof($file))
  {
      $list[] = (fgetcsv($file));
  }
fclose($file);

$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');

$list = array_filter($list);
outputCSV($list);

function outputCSV($list) {
    $output = fopen("php://output", "w");

    foreach ($list as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
}
?>