0

A trivial use of PHP and frwite() to create/write to a text file.

However, is there a way to write a very large text string to a file using fwrite?()? I assume there is, and that it involves some form of buffer management. The PHP docs don't seem to have this covered.

Sample code:

$p = "Some really large string ~ 100-250K in size"
$myFile = "testp.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
set_file_buffer($fh, 1000000);
fwrite($fh, $p);
fclose($fh);

Believe it or not, this simply gets a file with the name of the file inside the file. Using a much smaller text string, it works as expected. Pointers to what I should do would be useful.


UPDATE:

Some of you are missing that I did try the above with a string of ~100K, and it didn't work. All I got in the output file was the name of the file!!!

thanks

::: 2ND UPDATE....

 never mind.. the whole thing was user error... god i need a drink... or sleep!
 thanks

  php/fwrite works as i thought it would/should.. nothing to see here..!
tom smith
  • 1,035
  • 7
  • 23
  • 39
  • Out of interest, where's this string coming from? – Bojangles Jan 08 '12 at 00:08
  • 1
    If you already have the entire string in memory, why does it matter if you use buffers or just write the whole string? Write the whole string and drop it from memory as quickly as possible... – landons Jan 08 '12 at 00:10
  • Have a look at http://stackoverflow.com/questions/4798025/what-is-the-best-way-to-write-a-large-file-to-disk-in-php – Niklas Lindblad Jan 08 '12 at 00:10
  • Have you actually tried `fwrite($fh, 'a very large string')`? Didn't it work? – deceze Jan 08 '12 at 00:11
  • I agree this *should* work without any messing about - but if it doesn't, can't you just loop and write it in chunks with `substr()`? – DaveRandom Jan 08 '12 at 00:14
  • 1
    `All I got in the output file was the name of the file!!!` Then you have an error in your code!!! – deceze Jan 08 '12 at 00:16
  • 1
    Believe it or not, after fixing the syntax error in your code it works perfectly fine as expected. Since this is obviously not the exact same code as you tested, I suspect you simply have a variable mixup somewhere and are overwriting your content with the file name at some point. – deceze Jan 08 '12 at 00:25

1 Answers1

1

There is no limit on how much data can be written to a stream (a file handle) in PHP and you do not need to fiddle with any buffers. Just write the data to the stream, done.

deceze
  • 510,633
  • 85
  • 743
  • 889