2012-05-31 27 views
0

我想在內存中創建一個文件,並在單擊按鈕時將其發送到瀏覽器。我期待下面的代碼來做伎倆:如何使用PHP將字符串作爲文件發送到瀏覽器?

<?php 

$content = 'This is supposed to be working... dammit'; 
$length = strlen($content); 

header('Content-Description: File Transfer'); 
header('Content-Type: application/pdf'); 
header('Content-Disposition: attachment; filename=testfile.txt'); 
header('Content-Transfer-Encoding: binary'); 
header('Content-Length: ' . $length); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Expires: 0'); 
header('Pragma: public'); 

echo $content; 
exit; 

?> 

而是我得到的字符串回顯。我的愚蠢的newb錯誤是什麼?

+4

打開你的PHP警告。在你的第一個'header()'之前,你可能會在瀏覽器中回顯一些東西,在這種情況下,所有的頭部語句都會被忽略。 – halfer

+0

你爲什麼要輸出PDF?我想這完全有可能是你的瀏覽器啓動了你的PDF閱讀插件,它看到了文本,並且正在渲染它。 – Brad

+0

我嘗試過各種內容類型,包括任意流和pdf ...也許這是我的apache設置... –

回答

2

你需要改變你的內容類型,這個工作對我來說,在FF和Chrome測試

<?php 
$content = 'This is supposed to be working... dammit'; 
$length = strlen($content); 

header('Content-Description: File Transfer'); 
header('Content-Type: text/plain');//<<<< 
header('Content-Disposition: attachment; filename=testfile.txt'); 
header('Content-Transfer-Encoding: binary'); 
header('Content-Length: ' . $length); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Expires: 0'); 
header('Pragma: public'); 

echo $content; 
exit; 
?> 
+0

不能從我的xampp工作:-(我想這是我...:' - ( –

0

「記住header()函數發送任何實際輸出之前,必須被稱作」(c

+0

)如果在調用header()之前發送任何輸出,PHP將會停止並顯示一個錯誤,它不會輸出字符串內容。 –

相關問題