PHP数组到csv - 总是重写文件

时间:2016-07-03 11:50:01

标签: php csv fputcsv

我试图将3个变量保存到csv文件中。我得到变量数据然后我创建一个包含它们的数组。我可以打开文件并编写它。我想在每个页面加载时存储以下数据: - referer - 用户代理 - 日期

我的问题是,在每个页面加载时,它会重写文件而不是仅仅输入新数据。

有什么想法吗? 每个评论都表示赞赏。

<?php

在session_start();

if ( !isset( $_SESSION["origURL"] ) )
$_SESSION["origURL"] = @$_SERVER["HTTP_REFERER"];

$referer = @$_SERVER['HTTP_REFERER'];
$userAgent = @$_SERVER['HTTP_USER_AGENT'];
$date = date('Y-m-d H:i:s');

$visitorData = array("referer", "userAgent", "date");
$result = compact($visitorData);
print_r($result);

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

foreach ($result as $fields) {
    fputcsv($fp, $result, $delimiter = ',', $enclosure = '"');
}

fclose($fp);
exit();

&GT;

1 个答案:

答案 0 :(得分:1)

正如@ splah58所说,您必须在追加模式下打开文件才能添加数据,如下所示:

if( !isset( $_SESSION["origURL"] ))
  $_SESSION["origURL"] = @$_SERVER["HTTP_REFERER"];

$referer = @$_SERVER['HTTP_REFERER'];
$userAgent = @$_SERVER['HTTP_USER_AGENT'];
$date = date('Y-m-d H:i:s');

$visitorData = array("referer", "userAgent", "date");
$result = compact($visitorData);
print_r($result);

$fp = fopen('file.csv', 'a'); // 'a' means 'append' instead of 'w' for 'writing' which always delete the file's content

foreach ($result as $fields) {
  fputcsv($fp, $result, $delimiter = ',', $enclosure = '"');
}

fclose($fp);
exit();