PDA

View Full Version : PHP script, just to read the first line.



Spike121
11-03-2007, 04:38 AM
I was wondering, is there a way to open a file, such as a .txt file, then only read the first line, then close the file again? Thanks in advance.

PS. Also, is there a way to write only to the first line, without wiping the whole .txt file? Thanks in advance again :)

Please help with both of the above.

tech_support
11-03-2007, 05:17 AM
Reading the first line:


$content = file('mytextfilename.txt');
//First line: $content[0];
echo $content[0];


For writing the first line, you can always overwrite the file by using:



$fp = fopen('mytextfilename.txt','w');
fwrite($fp,'newcontent');
fclose($fp);

Spike121
11-03-2007, 06:39 AM
Thanks for the reading first line part, but for the write part, I need it to write to the first line only. I already have it overwriting, but it's not what I need.

Thanks!

djr33
11-03-2007, 11:57 AM
$f = file_get_contents($pathandname);
$f = explode("\n",$f,2);
$f[0] = trim($f[0]);
echo $f[0]; //old stuff
$f[1] = trim($f[1]);
$file = fopen($f,'w');
fwrite($file,$newstuff."\n".$f[1]); //\n or \r\n on windows
fclose($file);