PHP下载一个csv文件然后创建2个文件

时间:2015-08-31 13:32:16

标签: php csv

因此,每当用户从站点下载.csv文件时,另一个.csv文件就会创建到我的../includes文件夹中,这意味着下载文件夹中有一个.csv文件下载,另一个.csv文件创建我的.php文件所在的位置。有没有办法防止我的.php文件中的文件被创建,而只是下载?谢谢!这是代码。

<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "envoy");
function db_connect() {

  $db = mysqli_connect(DB_HOST, DB_USER, DB_PASS) or die("ERROR!");
  mysqli_select_db($db, DB_NAME);

  return $db;
}

$db = db_connect();
date_default_timezone_set("EST5EDT");
$date = date('m-d-Y,h.i.sa');
$date2 = date('m/d/Y');
$filename = $date.'.csv';
$fp = fopen($filename,"w");

$sql2 = "SELECT sku as Sku,name as 'Brochure Name',location as Location FROM brochureinfo where modified LIKE '$date2' ORDER BY name  ";
$rs2 = mysqli_query($db, $sql2);
mysqli_close($db);

$row = mysqli_fetch_assoc($rs2);

$seperator = "";
$comma = "";

foreach ($row as $name => $value){
    $seperator.= $comma. ''.str_replace('','""',$name);
    $comma=",";

}
$seperator .= "\n";

echo $seperator;




mysqli_data_seek($rs2,0);

while ($row = mysqli_fetch_assoc($rs2)){

$seperator = "";
$comma = "";

foreach ($row as $name => $value){

            $value = str_replace( array( "\r" , "\n", "\r\n", "\n\r" ) ,'' , $value);
            $value = str_replace('</b><br>','',$value);
            $value = str_replace('<b>','',$value);
            $value = str_replace('<br>','',$value);
            $value = str_replace('<br />','',$value);

    $seperator.= $comma. ''.str_replace('','""',$value);
    $comma=",";

    }
$seperator .= "\n";

//putting the heading into the csv file
fputs($fp,$seperator);

}

header('Content-Type: text/csv');
header("Content-Disposition: attachment; filename=$date.csv");
header('Pragma: no-cache');
readfile($filename);

fclose($fp);

如果无法阻止,可能是一种更改创建位置的方法而不是我的包含文件夹可能是另一种?非常感谢你!

2 个答案:

答案 0 :(得分:0)

这是因为代码将CSV保存到本地文件,然后读取文件并将其发送到浏览器。要跳过本地创建,请评论/删除fopen()fputs()fclose()行,注释掉/删除$seperator = "";行,并将readfile($filename);替换为{{ 1}}此外,您必须先删除/评论代码中的echo $seperator;

使您的代码类似:

echo $seperator;

答案 1 :(得分:0)

您在发送文件之前正在服务器上编写该文件。你可以发送标题,然后像这样回显结果:

mysql (table name is accessNum) is
pagename(varchar(255)) = index.html,
today(date) = 2015-08-31,
tcount(int(11)) = 1,
totalcount(int(11)) = 1,