将数据库转换为 CSV 并将文件保存到服务器上的文件夹
我已经成功地将我的数据库导出为 csv 作为可下载文件.但是,我现在需要做的不是创建一个直接下载的 .csv 文件,而是将其保存到服务器上名为csv"的文件夹中.这是我当前导出的代码.我需要帮助保存到服务器部分.文件夹 (csv) 上的 CHMOD 为 777
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 ) . " ";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = " ";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . " ";
}
$line .= $value;
}
$data .= trim( $line ) . "
";
}
$data = str_replace( "" , "" , $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()
的调用.您已经在 $data
中正确格式化了 csv,因此写入过程很简单:
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
$data");
而不是 777
对 csv 文件夹的权限,它应该由 Web 服务器以 700
运行的用户拥有,或者由 Web 服务器用户作为组拥有770
.
Rather than 777
permissions on the csv folder, it should be owned by user the web server runs as with 700
, or group-owned by the web server user as 770
.
相关文章