Following your own example, one way to do the process would be to create a function and get the line specified by configuring the function's arguments.
In this case I used a array
to define the lines you need to capture.
The function returns a array
because it is best for you to be able to organize.
Description:
array getLines ( mixed $handle , array $lines)
-
$ handle Can be a
string
with the file path or a resource
returned from a fopen
-
$ lines Must be an array with the specified lines
The function:
function getLines($context, $lines) {
$isResource = false;
if (is_resource($context)) {
//Você pode definir um resource ao invés de um "path"
$fp = $context;
$isResource = true;
} else if (is_file($context)) {
$fp = fopen($context, 'r');
} else {
return false;
}
$i = 0;
$result = array();
if ($fp) {
while (false === feof($fp)) {
++$i;
$data = fgets($fp);
if (in_array($i, $lines)) {
$result[] = $data;
}
}
}
//Pega última linha
if ($i !== 1 && in_array('last', $lines)) {
$result[] = $data;
}
if ($isResource === true) {
//Não fecha se for resource, pois pode estar sendo usada em outro lugar
$fp = null;
} else {
fclose($fp);
}
$fp = null;
return $result;
}
Examples:
Reading lines 1 and 2 of a file:
print_r(getLines('/home/user/test.txt', array(1, 2)));
Reading lines 3, 6, 11, 12, and 13 of a resource:
$res = fopen('data.txt', 'r');
print_r(getLines($res, array(3, 6, 11, 12, 13)));
...
fclose($res);
Reading the first and last line:
print_r(getLines('/home/user/test.txt', array(1, 'last')));