File handling - write to first line of file

1 view
Skip to first unread message

zeesh...@gmail.com

unread,
Apr 29, 2007, 3:05:14 PM4/29/07
to phpguru
This snippet let's you insert data at the beginning of a file.
it reads the contents and adds new data to the first line of the file.
after this it joins the lines and writes them back to the file again.

addcontents.php

<?php
// your new data + newline
$new_line = 'some new data here'."\n";

// the filepath
$file = 'temp/file.txt';
// the old data as array
$old_lines = file($file);
// add new line to beginning of array
array_unshift($old_lines,$new_line);
// make string out of array
$new_content = join('',$old_lines);
$fp = fopen($file,'w');
// write string to file
$write = fwrite($fp, $new_content);
fclose($fp);
?>

extract from http://fundisom.com/phpsnippets/snip/file_handling/write_to_first_line_of_file/

Reply all
Reply to author
Forward
0 new messages