Monday, July 23, 2007

File Handling - Write to File First Line

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.
// your new data + newline
$new_line = 'some new data here'."\n";
// the filepath
$file = 'emp/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);
?>

No comments: