Search file and display content

Asked

Viewed 558 times

2

I need to get a arquivo.txt, print it on screen and enter the total lines, but would like to "search" the file in any system directory

<?php

$arquivo = fopen('arquivo.txt', 'r');

while (!feof ($arquivo)) {
  $linha = fgets($arquivo);
  echo $linha."<br>";
}
fclose ($arquivo);

$linhas = count( file('arquivo.txt' ) );

echo "<br />Quantidade de linhas : ".$linhas;

?>
  • What is the difficulty? Your code is working?

  • No, it locks the browser...

  • And this way that I made the.txt file is already inside the same folder as the.php file, I would like, for example, a field that searches this file...

1 answer

2


To fetch all files called arquivo.txt in any subdirectory from the root of the application, you can use the function glob:

$files = glob("./**/*/arquivo.txt");

In this case, $files will be a list of all name files arquivo.txt in any sub-directory. To display the contents of each, as well as the number of lines, just do:

foreach ($files as $file)
{
    $content = file_get_contents($file);
    $lines = substr_count($content, "\n");

    echo "Conteúdo: ", $content, PHP_EOL;
    echo "Linhas: ", $lines, PHP_EOL;
}

Whereas you have the following file structure:

index.php
/foo
   /bar
      arquivo.txt

Whereas the content of arquivo.txt is supposedly:

Pellentesque in ipsum id orci porta dapibus. 
Vivamus suscipit tortor eget felis porttitor volutpat. 
Nulla quis lorem ut libero malesuada feugiat. 
Pellentesque in ipsum id orci porta dapibus. 
Curabitur aliquet quam id dui posuere blandit. 
Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. 
Sed porttitor lectus nibh. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. 
Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. 
Pellentesque in ipsum id orci porta dapibus.

The output of the program will be:

Conteúdo: Pellentesque in ipsum id orci porta dapibus. 
Vivamus suscipit tortor eget felis porttitor volutpat. 
Nulla quis lorem ut libero malesuada feugiat. 
Pellentesque in ipsum id orci porta dapibus. 
Curabitur aliquet quam id dui posuere blandit. 
Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. 
Sed porttitor lectus nibh. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. 
Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. 
Pellentesque in ipsum id orci porta dapibus.
Linhas: 9

Browser other questions tagged

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