Forum Moderators: coopster

Message Too Old, No Replies

Reading a single line from a file

Reading a single line from a file

         

RedBaron

3:29 pm on Sep 16, 2004 (gmt 0)

10+ Year Member



Hello,

I'm a noobie to PHP, and I'm trying to convert my asp scripts to php. In asp I can read a text file line by line like this.

<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")

Set f=fs.OpenTextFile(Server.MapPath("FileName.txt"), 1)
strLine1 = (f.ReadLine)
strLine2 = (f.ReadLine)
strLine3 = (f.ReadLine)
f.Close

Set f=Nothing
Set fs=Nothing
%>

I need to assign line 1 to one variable line 2 to a different variable and so on. Any help is greatly appreciated. Btw, I'm using php4.

Thanks

mincklerstraat

4:08 pm on Sep 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



check out function file() - [be2.php.net...]

$var = file('filename');
then $var[0] is the first line, $var[1] the second, etc;
echo '<pre>';
foreach($var as $k => $v){
echo '<br />line '.$k is '.htmlentities($v);
}
echo '</pre>';

have fun with file() and do some cool and groovy stuff with arrays.

coopster

4:44 pm on Sep 16, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



And Welcome to WebmasterWorld, RedBaron!

RedBaron

6:09 pm on Sep 16, 2004 (gmt 0)

10+ Year Member



Thanks guys and I'm glad to be a new member of WebmasterWorld.com.

I'm able to read the lines correctly now, but after I edit a line and try to write it back to the file it screws up on me.

$var = file('docs/FileName.txt');

$LineVar1 = $var[0] + 1;
$LineVar2 = $var[1];
$LineVar3 = $var[2];
$LineVar4 = $var[3];

$Data = $LineVar1 . $LineVar2 . $LineVar3 . $LineVar4;

$file = 'docs/FileName.txt';
$file = fopen($file, 'w');
fwrite($file, $Data);
fclose($file);

- Text file before -
1
2
3
4

- Text file after -
22
3
4

Thanks in advance.

mykel79

9:33 pm on Sep 16, 2004 (gmt 0)

10+ Year Member



The file() function leaves the newline character at the end of each line. So you would have to trim the newline, do the math, then add it again. Something like:
$LineVar1 = trim($var[0]) + 1."\n";