将数据库转换为CSV并将文件保存到服务器上的文件夹 [英] Convert Database to CSV and Save file to folder on server
问题描述
我已经成功将我的数据库导出为csv作为可下载文件。然而,我现在需要做的是,而不是创建一个直接的.csv文件,下载我需要它只是保存到服务器上名为csv的文件夹。这里是我当前导出的代码。我需要帮助在保存到服务器部分。文件夹(csv)上的CHMOD为777
$ today = date('Y-m-d');
$所有你需要添加的是对
$ select =SELECT * FROM goldpacks WHERE date ='$ today';
$ export = mysql_query($ select)或die(Sql error:。mysql_error());
$ fields = mysql_num_fields($ export);
for($ i = 0; $ i <$ fields; $ i ++)
{
$ header。= mysql_field_name($ export,$ i)。 \t;
}
while($ row = mysql_fetch_row($ export))
{
$ line ='';
foreach($ row as $ value)
{
if((!isset($ value))||($ value ==))
{
$ value =\t;
}
else
{
$ value = str_replace('','',$ value);
$ value =''。 $ value。 '\\'。\t;
}
$ line。= $ value;
}
$ data。 ;
}
$ data = str_replace(\r,,$ data);
if($ data ==)
{
$ data =\\\
(0)Records Found!\\\
;
}
header(Content-type:application / octet-stream);
header(Content-Disposition:attachment; filename = import.csv);
print$ header\\\
$ data;
file_put_contents()的调用
。p $ p>
$ data 中正确格式化了您的csv,因此写入过程很简单:// $ filename是你需要调用的文件
file_put_contents(/ path / to / csv /。$ filename,$ header\\\
$ data);
而不是csv文件夹的
777
权限应该由用户拥有的Web服务器以700
运行,或者由Web服务器用户以770
。I've have been successful in exporting my database to csv as a downloadable file. However what I now need to do is instead of creating a straight .csv file that's downloaded I need it to just save to a folder called "csv" on the server. Here is my code for the current export. I need help in the saving to the server part. CHMOD on the folder (csv) is 777
$today = date('Y-m-d'); $select = "SELECT * FROM goldpacks WHERE date = '$today'"; $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) ); $fields = mysql_num_fields ( $export ); for ( $i = 0; $i < $fields; $i++ ) { $header .= mysql_field_name( $export , $i ) . "\t"; } while( $row = mysql_fetch_row( $export ) ) { $line = ''; foreach( $row as $value ) { if ( ( !isset( $value ) ) || ( $value == "" ) ) { $value = "\t"; } else { $value = str_replace( '"' , '""' , $value ); $value = '"' . $value . '"' . "\t"; } $line .= $value; } $data .= trim( $line ) . "\n"; } $data = str_replace( "\r" , "" , $data ); if ( $data == "" ) { $data = "\n(0) Records Found!\n"; } header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=import.csv"); print "$header\n$data";
解决方案All you need to add is a call to
file_put_contents()
. You already have your csv correctly formatted in$data
so the write process is simple:// $filename is whatever you need the file to be called file_put_contents("/path/to/csv/" . $filename, "$header\n$data");
Rather than
777
permissions on the csv folder, it should be owned by user the web server runs as with700
, or group-owned by the web server user as770
.这篇关于将数据库转换为CSV并将文件保存到服务器上的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文