将数据库转换为 CSV 并将文件保存到服务器上的文件夹 [英] Convert Database to CSV and Save file to folder on server

查看:46
本文介绍了将数据库转换为 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.

这篇关于将数据库转换为 CSV 并将文件保存到服务器上的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆