2012-01-03 61 views
0

我試圖在PHP中將數據寫入一個簡單的txt文件,然後打開它,以便用戶可以下載它。我想保持它非常輕巧,當我運行此我得到:
PHP中的輕量級fopen技術

Warning: fopen(testFile.txt) [function.fopen]: failed to open stream: File exists in /home/user/script.php on line 9 

這裏是我的示例代碼:

<?php 

$File = "sample.txt"; 
$write = fopen($File, 'w') or die(); 
$stringData = "asdfjkl;"; 
fwrite($write, $stringData); 
fclose($write); 

$open = fopen($File, 'x') or die(); 
fclose($open); 

?> 

謝謝!

+0

關於['fopen'](http://www.php.net/manual/en/function.fopen.php)的文檔。 **模式x **:如果文件已經存在,則fopen()調用將返回FALSE並生成E_WARNING級別的錯誤。 – 2012-01-03 22:31:46

+0

雖然我似乎無法找到該文件。 – user1062058 2012-01-03 22:40:33

回答

1

使用file_put_contents寫入文件:

$filename = "sample.txt"; 
$stringData = "asdfjkl;"; 
file_put_contents($filename, $stringData); 

然後,當你要輸出的文件使用的內容:

$filename = "sample.txt"; 
readfile($filename); 

如果你想要的文件內容的形式返回字符串而不是立即輸出使用file_get_contents而不是readfile

+0

感謝您的回覆,以您的示例顯示瀏覽器中的內容。我是否使用fopen做提示下載而不是使用readfile? – user1062058 2012-01-03 22:37:18

+0

@ user1062058:要打開下載提示,您需要發送某些標題標誌。查看['readfile'文檔頁面](http://php.net/manual/en/function.readfile.php)中的示例。 – 2012-01-03 22:40:02

+0

感謝user1和Rocket,並不太確定那裏有什麼功能。謝謝! – user1062058 2012-01-03 22:44:41