12

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.

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"); ?> 
2
  • 2
    then don't echo it, write it to a file and remove the header() Commented Sep 13, 2012 at 2:48
  • 1
    why not just use this fputcsv? Commented Sep 13, 2012 at 2:49

3 Answers 3

13
  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);
    
Sign up to request clarification or add additional context in comments.

5 Comments

Thats awesome Hernan. But file is saving in directory as well as downloading. I want it to be saved only. Please help
How can I save this epay*.csv into a different directory?
$directory = "/tmp/"; // Or the directory you want $fd = fopen ( $directory . $cvs_filename, "w");
I am getting error Warning: fopen(/store/secure/mas/) [function.fopen]: failed to open stream: No such file or directory in /getdetails.php on line 16 Warning: fputs(): supplied argument is not a valid stream resource in /getdetails.php on line 40 Warning: fclose(): supplied argument is not a valid stream resource in /getdetails.php on line 43
$filename="ePay"; $directory = "/store/secure/mas/"; $csv_filename = $filename."_".date("Y-m-d_H-i",time()).".csv"; //$fd = fopen ($csv_filename, "w"); $fd = fopen ( "$directory" . $cvs_filename, "w");
11

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.