10

我是 PHP 新手。我正在创建一个脚本,它应该使用我的数据库中的一些数据创建一个 csv 文件,并将其保存到我服务器上的目录中。

我以某种方式做到了,但这个文件总是在下载。我不希望它下载。它应该只保存到一个目录中。

这是为您提供帮助的完整代码。

请帮助我。

<?php
$MYSQL_HOST="localhost";
$MYSQL_USERNAME="root";
$MYSQL_PASSWORD="";
$MYSQL_DATABASE="paesana";
$MYSQL_TABLE="ds_orders";
mysql_connect( "$MYSQL_HOST", "$MYSQL_USERNAME", "$MYSQL_PASSWORD" ) or die( mysql_error( ) );
mysql_select_db( "$MYSQL_DATABASE") or die( mysql_error( $conn ) );


$filename="ePay";
$csv_filename = $filename."_".date("Y-m-d_H-i",time()).".csv";

header("Content-Type: application/vnd.ms-excel");

$today="2008-12-21";
$sql = "SELECT * FROM $MYSQL_TABLE where cDate='$today'";

$result=mysql_query($sql);

if(mysql_num_rows($result)>0){

$fileContent="Beneficiary Name,Beneficiary Account No,Beneficiary Bank Code,Transaction Amount,Narration\n";
    while($data=mysql_fetch_array($result))
    {
    $fileContent.= "".$data['customer_id'].",".$data['oNum'].","."$today".",".$data['cShipService']." ".$data['cShipMethod'].",".$data['cEmail'].",".$data['ccType'].",".$data['cShipInstruct'].",".$data['cShipFname']." ".$data['cShipLname']."\n";
}


$fileContent=str_replace("\n\n","\n",$fileContent);
    echo $fileContent;
}
header("content-disposition: attachment;filename=$csv_filename"); ?> 
4

3 回答 3

12
  1. 如果您不想下载结果,请删除标题。

  2. 在这一行之后:

    $csv_filename = $filename."_".date("Y-m-d_H-i",time()).".csv";
    

    添加:

    $fd = fopen ($csv_filename, "w");
    
  3. 代替:

    echo $fileContent;
    

    利用

    fputs($fd, $fileContent);
    
  4. 不要忘记关闭您的文件

    fclose($fd);
    
于 2012-09-13T02:56:36.640 回答
11

您可以使用以下代码:

$data_array = array (
            array ('1','2'),
            array ('2','2'),
            array ('3','6'),
            array ('4','2'),
            array ('6','5')
        );

$csv = "col1,col2 \n";//Column headers
foreach ($data_array as $record){
    $csv.= $record[0].','.$record[1]."\n"; //Append data to csv
}

$csv_handler = fopen ('csvfile.csv','w');
fwrite ($csv_handler,$csv);
fclose ($csv_handler);

echo 'Data saved to csvfile.csv';
于 2014-07-03T13:10:09.183 回答
2

Try...

Simple way to create csv file.

<?php 
mysql_connect('hostname', 'username', 'password');
mysql_select_db('dbname');
$qry = mysql_query("SELECT * FROM tablename");
$data = "";
while($row = mysql_fetch_array($qry)) {
  $data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
}
$file = 'file.csv';
chmod($file, 0777);
file_put_contents($file, $data);
?>
于 2014-05-14T12:51:50.080 回答