How to open a file using php?

1

Good afternoon everyone !!

I'm trying to implement a program where I have to get .txt files from a folder, open them and grab the contents of this file to store in the database, I'm having trouble opening the file and viewing the contents using variables in PHP.

<?php 

$extensions = array('txt'); // image extensions
$result = array();
$directory = new DirectoryIterator('C:\Users\Fernando\Desktop\Imagens produto\APPLE'); // directory to scan
$dir = "C:/Users/Fernando/Desktop/Imagens produto/APPLE"; 
foreach ($directory as $fileinfo) {
    if ($fileinfo->isFile()) {
        $extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION));
        if (in_array($extension, $extensions, $dir)) {
            $result[] = $fileinfo->getFilename();

                 $conteudo =$dir."/".$fileinfo; //fiz uma gambiarra para juntar o diretorio com o nome do arquivo, para poder abrir em uma variavel com o caminho inteiro do arquivo
    //echo $conteudo."<br>";


        }
    }



}

   $a = open($conteudo);
    echo $a."<br>";
    /*while (!feof ($a)){
        $x = fgets($a, 5120);

        echo $x."<br>";

    }
    fclose($a);*/






//print_r($extensions);

?> 
    
asked by anonymous 13.05.2016 / 19:38

2 answers

1

To read the TXT files of a directory, use the FileSystemIterator function combined with CallbackFilterIterator .

See:

 $files = new FileSystemIterator(__DIR__ . '/files');

 $txts = new CallbackFilterIterator($files, function ($file)
 {
       return $file->isReadable() && strtolower($file->getExtension() === 'txt');
 });


 foreach ($txts as $file) {
      $db->salvaText($file->openFile());
 }

FileSystemIterator - Itera with directories and files.

CallbackFilterIterator - Iterate over another iterator (in our case FileSystemIterator and, according to the last callback, iterate or not on a given element of the child iterator.

The callback - Checks if the file can be read and if it is TXT extension.

    
13.05.2016 / 21:56
0

Use this:

$myfile = fopen("meu_arquivo.txt", "r") or die("Impossivel abrir o arquivo!");
// Mostra no browser cada linha do arquivo
while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
}
fclose($myfile);
    
13.05.2016 / 21:37