2011-02-15 133 views
1

在我的網站中,我實現了以下功能:如果用戶點擊一個按鈕,它將觸發一個PHP函數,該函數會生成一個XML文件(該PHP函數由AJAX調用)。一切運行良好,但我想改變一件事:我不希望在服務器計算機上創建一個.XML文件;相反,我想讓用戶在本地保存.XML文件。我怎麼做?我的PHP腳本目前看起來像這樣:如何在PHP中將XML文件保存到本地文件系統(客戶端)?

$xml = new DOMDocument("1.0", "UTF-8"); 
$rootElement = $xml->appendChild($xml->createElement("SomeNodeName")); 
... 

// the following doesn't really work - xml doesn't get formatted :) 
$xml->formatOutput = true; 

// this creates the actual file and places it on server. that's not what i need 
$xml->save("MyXMLfile.xml"); 

感謝您的所有幫助。

+1

這個問題在這裏已經被問過很多次了,這裏有一個更好的問答http://stackoverflow.com/questions/1465573/forcing-to-download-a-file-using-php – Endophage 2011-02-15 21:07:38

+0

@Endophage:感謝我似乎並沒有覺得它特別有用,因爲我正在使用AJAX,這是我遇到的主要問題 - 我的頁面部分填充了xml內容;而我需要保存文件對話框。 ? 謝謝。 – Boris 2011-02-15 21:25:12

回答

1

每個網頁的內容有一個頭,所以如果你指定一個xml文件頭(通過使用與相應的代碼,header()功能,它會工作 這意味着做這樣的事情:

<?php 
header('Content-type: text/xml'); 

// set the filename 
header('Content-Disposition: attachment; filename="pwet.xml"'); 

// echo the content here 
echo $xml; // simply like this, maybe? 
相關問題