使用 PHP 创建 CSV 文件并将其保存到目录中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12398750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:29:11  来源:igfitidea点击:

Create CSV file using PHP and save it into directory

php

提问by user1667374

I am new to PHP. I was creating a script which should create a csv file with some data from my database and save it into a directory on my server.

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

I somehow done it but this file is always downloading. I dont want it to download. It should just save onto a directory.

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

Here is the full code for your help.

这是对您的帮助的完整代码。

Please help me on this.

请帮我解决这个问题。

<?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"); ?> 

回答by Hernan Velasquez

  1. If you don't want to download the results, get rid of the headers.

  2. After this line:

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

    Add:

    $fd = fopen ($csv_filename, "w");
    
  3. Instead of:

    echo $fileContent;
    

    Use

    fputs($fd, $fileContent);
    
  4. Don't forget to close your file

    fclose($fd);
    
  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);
    

回答by Diwakar upadhyay

You can use the following code:

您可以使用以下代码:

$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';

回答by Indrajeet Singh

Try...

尝试...

Simple way to create csv file.

创建 csv 文件的简单方法。

<?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);
?>