Get line from a file

Asked

Viewed 788 times

2

I am reading a txt file in PHP, and I want to get the first line and the last line to write. I used this code to read the whole file line by line. But what I want is just a few lines.

$fp = fopen($fichier,"r");

if ($fp) {

    while (!feof($fp)) {
        $texte = fgets($fp);

        if(strpos($texte,"--") === false ) 
        {} 
        else { 
            $titre = $texte; /
            echo $titre."<br>";
        } 

    }
fclose($fp);}
  • wants only to get the first and last line to write where?

3 answers

1

0

Use the function file.

Ex:

<?php
$linhas = file('arquivo.txt');

This function returns the contents of the file with one line per array entry. From there, just manipulate the line you want through the index of the array and then rewrite the file with the contents of the array (if applicable):

<?php
file_put_contents('arquivo.txt', implode(PHP_EOL, $linhas));
  • In the performance of the SERVER this method is not very good because it can consume more memory than necessary.

  • @Guilhermenascimento yes. If it is a large file, the procedure can be costly.

  • What I mean is that if he wishes the first and last line, the best procedure would be feof combined fgets one more increment ++$i to detect the line the user requested. Thus the expense would be as little as possible.

  • Guilherme Nascimento, if the file is small, for example, about 5 lines, the use of file() is better and the use of fgets becomes heavier.. Therefore, what is "right" or "wrong" depends on the case.

0


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')));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.