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 with 700
, or group-owned by the web server user as 770
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With