我已经尝试了几个小时了,但没有成功。我已使用以下命令成功在浏览器中将 CSV 输出为下载:
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
Run Code Online (Sandbox Code Playgroud)
不过,我希望该输出现在转到 FTP 服务器,我已经对连接和临时文件部分进行了排序,但似乎无法编辑文件来输出我的结果。
// create empty variable to be filled with export data
$csv_export = '';
for($i = 0; $i < $field; $i++) {
$csv_export.= mysql_field_name($query,$i).',';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysql_field_name($query,$i)].'",';
}
$csv_export.= '
';
}
Run Code Online (Sandbox Code Playgroud)
上面是获取查询数据并将其放入 CSV 的部分,我尝试将 fputs 和 fputcsv 合并到循环中以将行写入文件。
//Upload the temporary file to server
ftp_fput($ftpstream, '/httpdocs/.../abandoned.csv', $temp, FTP_ASCII);
$fp = fopen('var/www/vhosts/.../abandoned.csv', 'w');
fputs($fp, '$csv_export');
fclose($fp);
echo($csv_export);
Run Code Online (Sandbox Code Playgroud)
因此,回显输出效果绝对没问题 - 我想要的只是将回显数据写入 CSV 文件并上传到 FTP。
我得到的错误是:
Array ( [type] => 2 [message] => fclose() expects parameter 1 to be resource,
boolean given
Run Code Online (Sandbox Code Playgroud)
所以 fp 导致了问题......是在打开阶段还是在写入 csv_export 时?
提前致谢。
尝试这个
//Write the contents to the temp file
fputs($temp, $csv_export);
//upload the temp file
ftp_fput($ftpstream, '/httpdocs/.../abandoned.csv', $temp, FTP_ASCII);
//close the temp file
fclose($temp);
Run Code Online (Sandbox Code Playgroud)
您当前的代码正在创建一个空文件,上传它,然后创建一个单独的文件。即使你让它在本地服务器上运行,这也是一个不必要的步骤。