Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to insert a new line into the begin of file?

Status
Not open for further replies.

alan123

MIS
Oct 17, 2002
149
0
0
US
I have a text file, and want to insert line "<?php ... ?>" by PHP to the top of this file, I tried:
Code:
$file = "test.txt";
$fp = fopen($file,'r+');
$newline = "<?php echo "$abc"; ?>";
fwrite($fp,$newline);
fclose($fp);

but this will replace the character in text.txt with new line added, I need insert this line instead of replacement.
how can I do that?
 
I think you need to read the file into a temp variable, or use a temp file.
 
Hello

It's effectively necessary to pass by a temporary variable =)

Code:
1   <?php 
2     $new_line = "some new text here\n"; 
4     file = "file.txt"; 
6     old_lines = file($file); 
8     array_unshift($old_lines,$new_line); 
10    $new_content = join('',$old_lines); 
12    $fp = fopen($file,'w'); 
13    $write = fwrite($fp, $new_content); 
15    fclose($fp); 
16  ?>

@+
 
I was at first confused when I read your question - a new line? Oh, A "new line", as an additional line, not a "new line \n" character. Howeverm here's a head up:
Be aware that different OS's use different newline characters. Some use "\n", or "\r\n" or "\n\r".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top