Get line from file

2

I'm reading a txt file in PHP, and I want to get the first line and the last line to be able to write. I used this code to read the entire 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);}
    
asked by anonymous 23.12.2014 / 18:57

3 answers

0

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')));
    
23.12.2014 / 19:38
1

The 1st line is easy, just use fgets as you are already using. To get the last line without having to read the whole file use the ReverseFile class of this Stackoverflow response in English here:

link

    
23.12.2014 / 19:22
0

Use the file function.

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 any):

<?php
file_put_contents('arquivo.txt', implode(PHP_EOL, $linhas));
    
23.12.2014 / 19:18