Working with text files - Writing data into a text file
(Page 3 of 10 )
You may think writing into a text file using PHP functions is hard. Actually it is easier than you think. By using the fwrite() function or fputs() function, PHP writes data to the opened file. fputs() is an alias to fwrite().
<?php $fp = fopen( "notes/data/names.txt" , "w" ); $inputString = 'Some text'; fwrite( $fp, $inputString ); ?> |
This tells PHP to write the string stored in $inputString to the file pointed to by $fp.Here is a another simple example of using fwrite() and hopefully, you would get an understanding about the parameters.
<?php $inputString = "This is the first line.\nThis is the seconds line.\nThis is the third line.";
$fp = fopen( "notes/data/names.txt" , "w" ); fwrite( $fp, $inputString ); ?> |
You may be wondering what the '\n' stands for inside $inputString? If we plan to write some sentences line by line in a text file, line breaks should be called as '\n'. When you want to write several lines into a text file, in one PHP line, you can easily use this character to the break the links. Refer to this link for more info : http://us2.php.net/manual/en/function.fwrite.php
Next: Closing a text file >>
More Programming Basics Articles
More By Codewalkers