2015-10-07 157 views
-1

我寫了一個腳本,在其中創建CSV文件並將其保存在我的服務器中的目錄中。 CSV文件包含來自查詢的屬性。 整個過程使用Jquery和Ajax單擊按鈕執行。從服務器下載CSV文件到本地目錄

我現在想要做的是能夠在本地保存生成的CSV。我發現了類似的問題,但是我還沒有找到答案如何創建一個對話框,它將提示客戶指定保存文件的位置。

這是我的jQuery代碼部分:

var nodeId = 'something'; 
var ajaxurl = 'requestsII/exportNodeData.php', // script to run 
     data = {nodeId:nodeId}; // data to pass 
     $.post(ajaxurl, data, function (response) {  
       //alert(response); 

     }); 

這是我的PHP腳本:

header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename=file.csv"); // EDITED 

if ($db) { 
    $stmt = $db->prepare('SELECT kodpop AS "ΚΩΔΙΚΟΣ ΚΟΜΒΟΥ",itemcode AS "ΚΩΔΙΚΟΣ ΕΞΟΠΛΙΣΜΟΥ",temaxia AS "ΤΕΜΑΧΙΑ",status AS "STATUS" FROM bom WHERE type IN (:typeI, :typeII) AND kodpop = :nodeId'); 
    $stmt->execute(array('typeI' =>$typeI,'typeII' => $typeII,'nodeId' => $nodeId)); 

    #$results=$stmt->fetchAll(PDO::FETCH_OBJ); 
    #$json=json_encode($results); 
    #echo($json); 

    $filename = '/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/'.$nodeId.'.csv'; 

    $data = fopen($filename, 'w'); 

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
     fputcsv($data, $row); 
    } 

    fclose($data); 

} 

echo($data); // EDITED 

的問題是我怎麼能下載本地我的PHP腳本中創建CSV文件?

回答

0

畢竟我沒有用上面的方法,我做的是,工作正常其更直接:

var ajaxurl = 'exportNodeData.php', // script to run 
       data = {nodeId:nodeId}; // data to pass 
       $.post(ajaxurl, data, function (response) {  
        document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip'; 

       }); 

這是ajax請求,我爲了創建CSV文件(它也被壓縮)執行。然後我用這條線:

document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip'; 

爲了強制下載文件。

1

試試這個代碼

header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename=file.csv"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 

echo "record1,record2,record3\n"; 

編輯

試試這個代碼

if ($db) 
{ 
    $stmt = $db->prepare('SELECT kodpop AS "ΚΩΔΙΚΟΣ ΚΟΜΒΟΥ",itemcode AS  "ΚΩΔΙΚΟΣ ΕΞΟΠΛΙΣΜΟΥ",temaxia AS "ΤΕΜΑΧΙΑ",status AS "STATUS" FROM bom WHERE type IN (:typeI, :typeII) AND kodpop = :nodeId'); 
$stmt->execute(array('typeI' =>$typeI,'typeII' => $typeII,'nodeId' => $nodeId)); 

#$results=$stmt->fetchAll(PDO::FETCH_OBJ); 
#$json=json_encode($results); 
#echo($json); 

$filename = '/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/'.$nodeId.'.csv'; 



header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename=".$filename); 


while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
    print_r($row); 
} 
} 
+0

我應該把它放在我的PHP腳本? – user1919

+0

我得到一個500服務器錯誤。 – user1919

+0

你必須添加標題(前兩個標題就足夠了)並且回顯你的數據。如果你有任何進一步問題,請告訴我。 –

相關問題