如果文件已存在,则使用其他名称创建CSV

时间:2015-01-27 05:57:33

标签: php csv

我一直在使用数据数组创建CSV,目前如果CSV已存在于同一位置,则会返回错误。

因此,我有可能让它在同一地点创造另一个。

示例:如果是一个名为 report.csv 的csv来创建一个具有自动生成名称的新名称,例如 report(1).csv

$exportBaseDir = 'C:/Users/myflder';
$fileD = "report".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
    fputcsv($fp, $fields,',');
}
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary");
fclose($fp);

1 个答案:

答案 0 :(得分:1)

最后的工作实例..谢谢你的想法

$exportBaseDir = 'C:/Users/myflder';
$fileD = "report".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
if(file_exists($basePath) == false){
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
    fputcsv($fp, $fields,',');
}
}
else{
    $time_start = time();
    $exportBaseDir = 'C:/Users/myflder';
    $fileD = "report"."#".$time_start.".csv";
    $basePath = "$exportBaseDir/weeklyReport/$fileD";
        $fp = fopen($basePath, 'w');
        $header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
        fputcsv($fp, $header, ',');
        foreach ($tables as $fields) {
            fputcsv($fp, $fields,',');
        }
}