我试图从数据库中获取数据并将其显示在CSV文件中,该文件既可下载又可通过电子邮件发送给某人。我设法让可下载的文件工作,它显示所有正确的数据。它还会向必要的人发送CSV文件,但该CSV文件为空,并且不会显示任何数据。
这是我的代码:
$myroot = "../../";
include($myroot . "inc/functions.php");
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=surveys.csv');
$output = fopen('php://output', 'w');
// Create CSV file
fputcsv($output, array('Name', 'Branch', 'Website','Company', 'Question1', 'Question2', 'Question3', 'Question4', 'Question5'));
$mysql_connection = db_connect_enhanced('*****','*****','*****','*****');
$query='SELECT * FROM *****.*****';
$surveys = db_query_into_array_enhanced($mysql_connection, $query);
$count = count($surveys);
$data = array();
for($i=0; $i<=$count; $i++){
$data[] = array($surveys[$i]['FeedbackName'], $surveys[$i]['BranchName'], $surveys[$i]['FeedbackWebsite'], $surveys[$i]['FeedbackCompany'], $surveys[$i]['Question1'], $surveys[$i]['Question2'], $surveys[$i]['Question3'], $surveys[$i]['Question4'], $surveys[$i]['Question5']);
}
foreach( $data as $row )
{
fputcsv($output, $row, ',', '"');
}
fclose($output);
$encoded = chunk_split(base64_encode($output));
// create the email and send it off
$subject = "File you requested from RRWH.com";
$from = "*****@*****.com";
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-Type: multipart/mixed;
boundary="----=_NextPart_001_0011_1234ABCD.4321FDAC"' . "\n";
$message = '
This is a multi-part message in MIME format.
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit
Hello
We have attached for you the PHP script that you requested from http://rrwh.com/scripts.php
as a zip file.
Regards
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: application/octet-stream; name="';
$message .= "surveys.csv";
$message .= '"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="';
$message .= "surveys.csv";
$message .= '"
';
$message .= $encoded;
$message .= '
------=_NextPart_001_0011_1234ABCD.4321FDAC--
';
mail("*****@*****.com", $subject, $message, $headers, "-f$from");
我花了一天半的时间,但我看不出这个问题。有人可以指出我为什么附加的CSV文件是空的吗?
我变得有点绝望和压力:(请有人帮助我。
答案 0 :(得分:0)
base64_encode()
期望参数为字符串,并为其提供(已关闭)资源。
尝试将资源读入字符串,或者在写入资源时使用file_get_contents
或构建字符串。
更新
尝试并替换
foreach( $data as $row )
{
fputcsv($output, $row, ',', '"');
}
fclose($output);
$encoded = chunk_split(base64_encode($output));
通过
$myoutput = '"Name","Branch","Website","Company","Question1","Question2","Question3","Question4","Question5"';
foreach( $data as $row )
{
$myoutput .= "\"".implode('","',$row)."\"\n";
fputcsv($output, $row, ',', '"');
}
fclose($output);
$encoded = chunk_split(base64_encode($myoutput));
这样,您在输出中写入的所有内容也会写入新变量($myoutput
)。由于这是一个字符串,您可以将其与base64_encode()
一起使用。