Reputation: 275
I'm trying to write data to a simple txt file in PHP and open it so the user can download it. I'd like to keep it very lightweight, when I run this I get:
Warning: fopen(testFile.txt) [function.fopen]: failed to open stream: File exists in /home/user/script.php on line 9
Here is my sample code:
<?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);
?>
Thank you!
Upvotes: 0
Views: 242
Reputation: 141839
Use file_put_contents to write to the file:
$filename = "sample.txt";
$stringData = "asdfjkl;";
file_put_contents($filename, $stringData);
Then when you want to output the contents of the file use:
$filename = "sample.txt";
readfile($filename);
If you want the file contents to be returned as a string instead of output immediately use file_get_contents instead of readfile
Upvotes: 1