Jean Patrik
Jean Patrik

Reputation: 11

Get specified line from file using php

how can get specified lines from file

$file_handle = fopen("file.txt", "rb");

while (!feof($file_handle) ) {
    $line_of_text = fgets($file_handle);
    $parts = explode(',', $line_of_text);

    //from line   01 to line 100  echo "Lines 1";
    //from line   100 to line 200  echo "Lines 2";
    //from line   400 to line 1000  do somthing
}       

fclose($file_handle);

I need this output

//from line 400 to line 1000 do somthing

//from line 100 to line 200 do somthing

Upvotes: 1

Views: 41

Answers (2)

chris85
chris85

Reputation: 23892

You can use the file function to pull each line of your file into an array. Then use a for loop to iterate through the lines you want.

Example:

$lines = file('yourfile'); 
for($i =399; $i < 1000; $i++){ 
     echo $lines[$i];
}

Upvotes: 0

Kane Cohen
Kane Cohen

Reputation: 1800

Question is a bit vague. But if $parts variable are where you keep your lines, then in this case you can use function array_slice to pick only lines that you're interested in.

For example:

$parts = file('yourfile.txt');
$parts1to100 = array_slice($parts, 1, 100);
$parts100to400 = array_slice($parts, 100, 300);
$parts400to1000 = array_slice($parts, 400, 600);

If you'll need more separate parts, then that would be a different case and might be better to create a separate function which accepts certain values and returns required parts without relying on multiple variables. But that's a different story.

Upvotes: 1

Related Questions