1

I want read a line in file text. EX line 5. Any body can help me????

$fp=fopen("test.txt",r)or exit("khong tim thay file can mo");
while(!feof($fp)){
    echo fgets($fp);
}
fclose($fp);

Thanks for read

cuong ngo
  • 11
  • 1
  • 3

3 Answers3

3

You can use the fgets() function to read the file line by line:

<?php 
$handle = fopen("test.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo $line.'<br/>';
    }

    fclose($handle);
} else {
    // error opening the file.
} 
?>
Abdus Sattar Bhuiyan
  • 3,016
  • 4
  • 38
  • 72
2
$myFile = "text.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2

PHP - Reads entire file into an array

Shunteno
  • 21
  • 1
0

Just put an incremental counter in your loop, only echo if that counter matches your requred line number, then you can simply break out of the loop

$required = 5;

$line = 1;
$fp=fopen("test.txt",r)or exit("khong tim thay file can mo");
while(!feof($fp)){
    if ($line == $required) {
        echo fgets($fp);
        break;
    }
    ++$line;
}
fclose($fp);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385