Page 1 of 1

Reading lines from a text file.

Posted: Tue Jun 28, 2005 3:58 am
by srirams
All,

I would like to know a method where by I can read the first line into a string variable and the rest of the lines into another variable.
For intance
$filename = 'file.txt';
$fp = fopen($filename, "r");

if file.txt has 3 lines.
line1
line2
line3
I should store line1 into one variable $string1 and store the lines (line2 and line3) together into a string variable called string2.
Please suggest.

Regards

Posted: Tue Jun 28, 2005 4:06 am
by timvw

Code: Select all

$lines = file_get_contents('file.txt');
Now all the lines are in $lines[0], $lines[1], ... $lines[count($lines)-1]

Code: Select all

for ($i = 0; $i < count($lines); ++$i)
{
  ${"line" . $i } = $lines[$i];
}
And now they are in $line0, $line1, ...

Posted: Tue Jun 28, 2005 4:10 am
by Syranide
no, file does that
file_get_contents returns all "as-is" in a string.

Posted: Tue Jun 28, 2005 4:10 am
by srirams
Hi,

But this will not store even the first line together.
I want the first line in a different string and the 2nd and 3rd into another string.

Posted: Tue Jun 28, 2005 4:12 am
by timvw
Meaby need to correct the syntax a little, but here is the idea:

Code: Select all

$fp = fopen('file.txt');
$i = 1;
while ($line = fread($fp, 2048))
{
  ${"line" . $i} = $line;
  ++$i;
}
fclose($fp);

Posted: Tue Jun 28, 2005 4:23 am
by srirams
How do I put line2, line3 and line4 into one string?

say
Cricket.
Warne the best. Murli is 2nd. Kumble might be 3rd.

Now cricket should be stored in string named $string1
Warne the best. Murli is 2nd. Kumble might be 3rd. these 3 lines should be stored together in $string2.

Hope this is clear now.

Posted: Tue Jun 28, 2005 5:26 am
by djot
This only works, if your file always has the structure you described (first line => string1, second-third-forth line => string2)

Code: Select all

$i = 1;
$string1='';
$string2='';

$fp = fopen('file.txt');
while ($line = fread($fp, 2048))
{
  if ($i==1) { $string1 = $line; }
  else { $string2 .= $line; }
  ++$i;
}
fclose($fp);

Posted: Tue Jun 28, 2005 10:12 am
by pickle
Here's my 2 cents:

Code: Select all

$file_contents = file('file.txt');
$string1 = current($file_contents);
while($string2 .= next($file_contents))
{
  //this is actually an empty loop, as the work is done in the condition
}

Posted: Tue Jun 28, 2005 11:59 am
by djot
You did spend many bytes for your comment in relation to the code length :)