我是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"); ?>
答案 0 :(得分:11)
如果您不想下载结果,请删除标题。
在这一行之后:
$csv_filename = $filename."_".date("Y-m-d_H-i",time()).".csv";
添加:
$fd = fopen ($csv_filename, "w");
而不是:
echo $fileContent;
使用
fputs($fd, $fileContent);
不要忘记关闭文件
fclose($fd);
答案 1 :(得分:7)
您可以使用以下代码:
$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';
答案 2 :(得分: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);
?>