Convert Database to CSV and Save file to folder on server

白昼怎懂夜的黑 提交于 2019-12-09 18:08:12

问题


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

回答1:


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 with 700, or group-owned by the web server user as 770.



来源:https://stackoverflow.com/questions/7000627/convert-database-to-csv-and-save-file-to-folder-on-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!