Following your own example, one way to do the process would be to create a function and take the specific line by configuring the arguments of the function.
In case I used a array
to set the lines you need to capture.
The function returns a array
, because it’s better for you to organize.
Description:
array getLines ( mixed $handle , array $lines)
- $Handle May be a
string
with the file path or a resource
returned from a fopen
- $Lines Must be an array of 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 Source:
$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')));
wants only to get the first and last line to write where?
– rray