2013-06-13 103 views
0

我試圖將MySQL查詢結果導出到遠程ftp服務器。使用php將mysql查詢保存爲csv文件使用php

我有下面的代碼,但我目前得到一個錯誤:

Warning: ftp_put() [function.ftp-put]: Opening ASCII mode data connection. in /home/hulamyxr/public_html/kisv2/xmltest/export.php on line 50

我認爲我的$file = $csv_filename;可能是問題,因爲這是獲取剛剛創建的CSV文件我本地服務器?

有什麼想法?

我的語法是:

<?php 
$host = 'localhost'; 
$user = 'un'; 
$pass = 'pwd'; 
$db = 'dbname'; 
$table = 'v2ReportingTable'; 
$file = 'export'; 
$datetime=date("Y-m-d H:i:s"); 
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error()); 

//Create a CSV for 
$result = mysql_query("SELECT * FROM dbname.v2ReportingTable"); 
if (!$result) die('Couldn\'t fetch records'); 
$num_fields = mysql_num_fields($result); 
$headers = array(); 
for ($i = 0; $i < $num_fields; $i++) 
{  
     $headers[] = mysql_field_name($result , $i); 
} 
$csv_filename = "export-" .$datetime.".csv"; 
$fp = fopen($csv_filename, 'w+'); 


if ($fp && $result) 
{ 
    fputcsv($fp, $headers); 
    while ($row = mysql_fetch_row($result)) 
    { 
     fputcsv($fp, array_values($row)); 
    } 
} 

//works till here 

$ftp_server = "ftp.server.co.za"; 
$ftp_user_name = "un"; 
$ftp_user_pass = "pw"; 
$file = $csv_filename; 
$remote_file = "/LocExports/".$file; 


// set up basic connection 
$conn_id = ftp_connect($ftp_server); 

// login with username and password 
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// upload a file 
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) { 
echo "successfully uploaded $file\n"; 
} else { 
echo "There was a problem while uploading $file\n"; 
} 

// close the connection 
ftp_close($conn_id); 
?> 

再次感謝

回答

1

,它會在正確的位置的文件,但是0KB文件,然後所有的FTP命令失敗。客戶端很可能在防火牆後面。要糾正這種用法:

<?php 

ftp_pasv($ resource,true);

?> 
+0

謝謝,這與結果相同。有任何想法嗎? – Smudger