How to open a file using php?

Asked

Viewed 718 times

1

Good afternoon, everyone!!

I’m trying to implement a program where I have to get files. txt from a folder, open them and grab the contents of this file to store in the database, I am facing difficulty to open the file and view the content 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);

?> 
  • 3

    http://php.net/manual/en/function.file-get-contents.php

  • 2

    You used a thousand functions to call the extension in the file, and the SplFileInfo (that is returned in each iteration of the DiretoryIterator) already has the method $file->getExtension(). You can simplify your code.

2 answers

1

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

Behold:

 $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 - Iterates with directories and files.

Callbackfilteriterator - Iterates over another iterator (in our case FileSystemIterator and, according to the past callback, iterates or not on a particular element of the child iterator.

callback - Checks whether the file can be read and whether it is from the TXT extension.

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);
  • 1

    The title implies that he wants to open a file, but the contents of the question imply that he wants to open more than one file present in a directory

  • "open the file and view the contents"

Browser other questions tagged

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