以防万一有人想将 CSV 文件保存到电子邮件附件的特定路径。然后可以如下进行
我知道我已经为新手添加了很多评论:)
我添加了一个示例,以便您可以很好地总结。
$activeUsers = /** Query to get the active users */
/** Following is the Variable to store the Users data as
CSV string with newline character delimiter,
its good idea of check the delimiter based on operating system */
$userCSVData = "Name,Email,CreatedAt\n";
/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
$userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file */
$todayDate = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName = 'Active Users '.$todayDate.'.csv';
$filePath = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file
/** Just in case if I run the script multiple time
I want to remove the old file and add new file.
And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);
/** Now you can send email with attachments from the $filePath */
注意:以下是增加
memory_limit和time limit的一个非常糟糕的主意,但我只是添加以确保是否有人面临连接超时或任何其他问题。确保在坚持之前找到一些替代方案。
您必须在上述脚本的开头添加以下内容。
ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');