How to get the first 3 lines of a file and then everything else

I have a txt file, for example:

This is line 1.

This is line 2.

This is line 3.

This is all the rest.

Lorem etc.

I want to use PHP to get the first three lines in the $ variable, and then get everything else in the document into the $ variable.

I had some success:

<?php

$file = fopen("text.txt","r");
$count = "0";

while(! feof($file))
  {
  $count++;

  if ($count=="1") {
  $line1 = fgets($file);
  }

  if ($count=="2") {
  $line2 = fgets($file);
  }

  if ($count=="3") {
  $line3 = fgets($file);
  }

//everything else?

}

echo $line1;
echo $line2;
echo $line3;
//echo $everythingelse;

fclose($file);

?>

The following works:

echo fgets($file);

But this is not so:

$line1 = fgets($file);

So A) what am I doing wrong with this, and B) how can I get the rest of the file, and C) is there a better way to implement this? I feel like my path is awkward and someone will offer something obvious that can do all this.

Thanks guys!

+3
source share
3 answers

A). if: , fgets while, , , , - . fgets, while , .

B). : , . ( )

<?php

$file = fopen("text.txt","r");
$count = "0";

while(!feof($file)) {
  $count++;    
    switch ($count) {
        case "1":
            $line1 = fgets($file);
            break;
        case "2":
            $line2 = fgets($file);
            break;
        case "3":
            $line3 = fgets($file);
            break;
        default: 
            $everythingelse .= fgets($file);
    }
}

echo $everythingelse;

fclose($file);

echo "\n\n\n\n\n\n";
echo "Plus, here is line one: ".$line1."\n";
echo "This is line three: ".$line3."\n";
echo "And finally, line two: ".$line2."\n";

( if , )

: Output screenshot

C) , , fgets (, , ). . , , , implode, .

+2

file(), . , array_splice(), , \n.

// Reads the file into an array
$lines = file($file);

// Cuts off everything after the first three
$the_rest = array_splice($lines, 3);
// leaving the first three in the original array $lines
$first_three = $lines;

// Stick them back together as strings by implode() with newlines
$first_three = implode("\n", $first_three);
$the_rest = implode("\n", $the_rest);
+4

You can do it:

$data = file("text.txt");
$beginning = implode(PHP_EOL,array_splice($data,0,3));
$end = implode(PHP_EOL,$data);

Used functions: file, implode, array_spliceand PHP_EOLconstant .

+2
source

All Articles