Ian Hoar
Ian Hoar

Reputation: 1184

PHP, skip first and last line of a text file using fgets

I'm trying to figure out how to skip the first and last line of a text file when I'm reading it while using fgets(). The first line could be solved with an if(!$firstLine), but I'm not sure how to ignore the last line or if my solution for ignoring the first line is the best choice.

Upvotes: 3

Views: 9590

Answers (5)

Kyle Gagnon
Kyle Gagnon

Reputation: 62

You might want to try exploding the file contents. It will help you alot! After that you will label it.

Upvotes: 0

femtoRgon
femtoRgon

Reputation: 33341

fgets($file); //Ignore the first line
$line = fgets($file);
$next = fgets($file); 
while ($next !== false) { //check the line after the one you will process next.  
                //This way, when $next is false, then you still have one line left you could process, the last line.
    //Do Stuff
    $line = $next;
    $next = fgets($file);
}

Upvotes: 10

ABM
ABM

Reputation: 19

try this

 $str= file_get_contents("file.txt");
 $arr = preg_split ("\n",$str);
 $n = count($arr);

$n is a number of lines

$str="";
for($i=0;$i<$n;$i++){
   if($i>0 && $i<($n-1)){ $str.=$arr[$i]}
   }
    /**Str without line 1 and final line */

Upvotes: -1

user557846
user557846

Reputation:

$lines = file('http://www.example.com/');//or local file

unset($lines[0]);
unset($lines[count($lines)-1)]);
$new_file = implode('', $lines); //may want to use line break "\n" for the join

Upvotes: 0

jorj
jorj

Reputation: 153

Unfortunately, file() will open file into "serial" stream (not sure if serial is right word), it means that you must read full file before detecting his end

Upvotes: -1

Related Questions