View Full Version : Reading file into an array then writing the edited array back to the file

11-01-2012, 08:08 PM
I have a small 10 line text file that holds a users 10 favorite songs. There is a page where the user can add a song to the list, at any position in the list he/she pleases. How can I read the file into an array, add their chosen song to that position in the array, then write the array back to the file for saving?

So far I have something like this:

//if tunes.txt has less than 10 songs
if($lineCount<=10) {

//get the supplied song name
$content = $_POST['songName'];

foreach($openedFile as $lineNumber => $songPosition) {

//write the supplied song name to the file
fwrite($openedFile, " $content"."\n");

//alert the user that the file was created and updated
print(" <strong>The file has been created and updated!</strong>");

//close the opened file

//if the file has 10 or more songs already
} else {

//warn the user the maximum number of songs is 10
print(" <strong>A maximum of 10 songs are allowed in the file</strong>");

} //end if lineCount <= 10

As of right now, all this does is add the supplied song to the end of the text file. I need to implement a "Position" feature as well.

Can anyone help me with this?

11-01-2012, 08:58 PM
What is $openedFile? You shouldn't be able to both iterate it in a foreach as well as write to it with fwrite.
With only 10 lines, its mucho easier than this:

$sFile = '/path/to/file.txt';

// $aEntries is now an array ordered by the lines in the file offsets 0 - 9 (10 lines)
// manipulate it as you see fit.

// put it back in
if (file_put_contents($sFile, implode(PHP_EOL, $aEntries)) !== false)
print 'File successfully written';
// all done.

Another option would be to use a random access file with an explicit maximum length for each record. Then you would simply write the data (null padded or pack()ed in binary) to the position desired. Wastes more space IMO, but would be useful if you have much larger files to work with since you can jump to any arbitrary record in the file.