我有一些 PHP 代码可以成功地将 MySQL 表导出到 CSV 文件。
我想添加到该代码中,因此 CSL 文件不是保存在本地,而是导出到/保存在外部 FTP 服务器上。
我当前的代码:
//open database connection
require ('../database-config.php');
//name the file
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');
//SQL Query for Data
$sql = "SELECT * FROM data;";
//Prepare Query, Bind Parameters, Excute Query
$STH = $dbh->prepare($sql);
$STH->execute();
//Export to .CSV
$fp = fopen('php://output', 'w');
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row
while ($row = $STH->fetch(PDO::FETCH_NUM)) {
fputcsv($fp,$row); // push the rest
}
fclose($fp);
我知道我需要添加一些新变量;
$ftp_server="ftp.remotersite.com";
$ftp_path="/path/to/somefile";
$ftp_username="username";
$ftp_userpass="password";
但是,我不确定使用 ftp_put
(或者应该是 ftp_fput
?)传输到外部目的地的最佳方式。
提前致谢。
最佳答案
如果你有ftp://
URL wrappers enabled ,直接在FTP服务器上打开文件即可:
$fp = fopen('ftp://username:password@ftp.example.com/path/to/somefile', 'w');
如果您没有启用包装器,请参阅:
Creating and uploading a file in PHP to an FTP server without saving locally
关于php - 在 PHP 中的外部 FTP 服务器上生成 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49970767/