Page 1 of 1

write info to a txt file

Posted: Sat Jan 05, 2008 7:37 am
by andylyon87
basically its dead simple all I want to do is write to a text file! The code is below, the problem isn't that I cant write to the file but why is it not adding the data to the end of the file?

The code is the simplified test Im using!

Code: Select all

<?
function write_file($filename,$newdata) {
          $f=fopen($filename,"w");
          fwrite($f,$newdata);
          fclose($f);  
   }

function append_file($filename,$newdata) {
          $f=fopen($filename,"a");
          fwrite($f,$newdata);
          fclose($f);  
   }
   
function read_file($filename) {
          $f=fopen($filename,"r");
          $data=fread($f,filesize($filename));
          fclose($f);  
          return $data;
   }
write_file("test.txt","This is my initial text\n");
append_file("test.txt","New text added\n");
 $data=read_file("test.txt");

   echo "Data in file : <b>$data</b>";  
  ?>
This returns:

Data in file : This is my initial text New text added

Surely there is meant to be a line break between "text" and "New" !

Posted: Sat Jan 05, 2008 9:02 am
by Oren
There is, see nl2br()

Posted: Sat Jan 05, 2008 9:32 am
by andylyon87
thanks for that. Dunno why I hadnt realised that!

Posted: Sat Jan 05, 2008 11:39 am
by Jonah Bron
First off, I suggest you use <?php instead of <?

I have seen posts where that caused problems. :)

Maybe replace line breaks with <br /> tags:?:

Posted: Sat Jan 05, 2008 11:48 am
by John Cartwright
PHPyoungster wrote:Maybe replace line breaks with <br /> tags:?:
Thats what nl2br() does

Posted: Sat Jan 05, 2008 1:39 pm
by Jonah Bron
I say, good show. :wink:

Cool.

Posted: Sat Jan 05, 2008 1:44 pm
by s.dot
There's nothing wrong with the text file, and depending on your purposes you may not want the <br />'s there. If you view the source of the output, you will see that the line break is there. If you're intending on viewing the text files (not in a web browser) don't use nl2br(). If you're intending on viewing them inside of a web page, use nl2br().

Posted: Sat Jan 05, 2008 1:48 pm
by Jonah Bron
Cha.