PHP and file handling - file structure

You have written to a file but messed it up because there are no line breaks between the two new entries.

New lines/carriage returns

Edit the names.txt file and make sure there is a blank line after the last entry ("Ringo"). If Pete is mentioned delete him and anyone else you added while practising!

Now edit filewrite.php and amend the existing code. You must use double quotes and not single so that the special characters which are in the FOPEN statement are processed by PHP and not just inserted literally.

$handle = fopen("./names.txt", "a");
fwrite($handle, "Pete\r\n");
fclose($handle);
        

If the file is being viewed on a Unix/Linux platform then the \r is not required as only Windows uses \r\n for a new line character. Either way will work though.

Whichever you use upload the page and try it. The page in the browser will be blank again but check the contents of names.txt either by downloading it or loading files.php in a browser. You should find Pete on the last line with a new blank line at the end. Whether you use Windows or Unix line breaks PHP will understand when it breaks the file up into lines. Add some more names.

Tabs, semi-colons or commas - multiple items on a line

Often you will also want to store more than one thing on a line in a file. Each line can be thought of as a record in a database and there may be more than one item of information in each record. To extend the current example:

George Harrison
        

The whole line is one record (his full name) but there are actually two separate items in there (first name and surname).

To help PHP to separate items you mark the dividing place with a special character. Traditionally a comma, semi-colon or tab is used. To include a tab when writing to the file us \t:

$handle = fopen("./names.txt", "a");
fwrite($handle, "Paul\tMcCartney\r\n");
fwrite($handle, "John\tLennon\r\n");
fwrite($handle, "George\tHarrison\r\n");
fwrite($handle, "Ringo\tStarr\r\n");
fwrite($handle, "Pete\tBest\r\n");
fclose($handle);
        

Delete names.txt from your server. Place the above code in filewrite.php in place of the existing chunk. Upload and view the page in the browser (remember it is supposed to be blank). Look again at the text file. You should now see full names with tabs between the first name and surname. Reading and manipulating file data

If you think you will need to use files with PHP you do need to practice this. The two exercises here will help but also use your imagination.An exercise in putting form data into files

submit to reddit Delicious Tweet