Move to next line when reading txt file in Php

Asked

Viewed 2,455 times

0

Good morning to you all! Guys, I’m relatively new to php, and in one of the jobs here at the company, I’m having a difficulty, which may seem simple, but n found solution in my searches, which is like skipping a line in a txt file.

What I want to do is simple, read a txt file, when I find a particular word, I need to jump to the next line and read those lines until the word is found again. I have more experience in java, and in java we have a method called readLine(), which automatically switches to the next line. I saw that in php there is this readLine(), but did not know how to apply, or it is different than what I use in java. Well, thank you in advance for your help and attention. Thank you!

  • 1

    If it’s a small file you can use file() which transforms the file into an array then use array_search() or in_array() to find the desired term. Has the classic version with fopen() and fgets()

2 answers

3

You can use the function fgets() to read line by line as in the example:

$handle = fopen("nome do arquivo.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
    // lê a linha
}

fclose($handle);
} else {
// caso dê erro
} 

Source: How to Read a File line by line in PHP

  • 2

    Thanks for your attention @Victor Gomes! I followed your example and can read line by line. What I can’t do now is after I find the word I want, get it to go to the next line, like this: while (($linha = fgets($arquivo)) !== FALSE) {

 if (strpos($linha, $palavra) !== FALSE) {

 } Gave to understand more or less?

2

Using the function readline, would that way:

$file = '/caminho/seu_arquivo.txt';

$linha_lida = 2;
if ( file_exists( $file ) && is_readable( $file ) ) {
    echo readLine($file, $linha_lida);
} else {
    echo "$file Não pode ser lido!";
}

Now to find a word in TXT, it would look something like this:

$searchthis = "palavra";
$matches = array();

$handle = fopen("/caminho/seu_arquivo.txt", "r");

if ($handle) {
      while (!feof($handle)) {
          $buffer = fgets($handle);
          if (strpos($buffer, $searchthis) !== FALSE) {
              $matches[] = $buffer;
          }
      }
  fclose($handle);
}

//mostra os resultados:
print_r($matches);

Browser other questions tagged

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