Reading lines from a text file.
Moderator: General Moderators
Reading lines from a text file.
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
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
Code: Select all
$lines = file_get_contents('file.txt');Code: Select all
for ($i = 0; $i < count($lines); ++$i)
{
${"line" . $i } = $lines[$i];
}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);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);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
}Real programmers don't comment their code. If it was hard to write, it should be hard to understand.