Move to next line when reading txt file in Php

0

Good morning everyone! Hi, I'm new to php and I'm looking for a way to get the most out of a php file.

What I want to do is simple, to read a txt file, when I find a certain 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 moves to the next line. I saw that in php there is this readLine() , but I did not know how to apply it, or it is different from what I use in java. Well, thank you in advance for your help and attention. Thanks!

    
asked by anonymous 19.04.2016 / 14:45

2 answers

3

You can use the fgets() function to read row 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

    
19.04.2016 / 14:56
2

Using the readLine function, it would look like this:

$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);
    
19.04.2016 / 15:02