在PHP中的外部FTP服务器上生成CSV文件

问题描述:

我有一些PHP代码可以成功将MySQL表导出到CSV文件.

I have some PHP code that successfully exports a MySQL table to a CSV file.

我想添加到该代码中,因此不是将CSL文件保存到本地,而是将其导出到外部FTP服务器上/保存在外部FTP服务器上.

I would like to add to that code, so instead of saving locally the CSL file is exported to/saved on an external FTP server.

我当前的代码:

//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);

我知道我需要添加一些新变量;

I know I'll need to add some new variables;

$ftp_server="ftp.remotersite.com";
$ftp_path="/path/to/somefile";
$ftp_username="username";
$ftp_userpass="password";

但是,我不确定使用ftp_put(或者应该是ftp_fput?)转移到外部目的地的最佳方法.

But, I'm not sure the best way to use ftp_put (or should it be ftp_fput?) to transfer to the external destination.

谢谢.

如果您具有

If you have ftp:// URL wrappers enabled, just open the file directly on FTP server:

$fp = fopen('ftp://username:password@ftp.example.com/path/to/somefile', 'w');


如果未启用包装程序,请参见:
使用PHP创建文件并将其上传到FTP服务器,而无需在本地保存


If you do not have the wrapers enabled, see:
Creating and uploading a file in PHP to an FTP server without saving locally