How do you read the content of every .txt file in a directory using PHP?

  • Thread starter Thread starter scopefragger
  • Start date Start date
S

scopefragger

Guest
I currently use the following code
"<?
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 500);
fclose($fh);
echo $theData;
?>"
this reads a single file, i need to read all files within the directory "selling" and have them displayed on 1 page
the folder will be dynamic and the filenames will be unknow, the code given by ryan only helps if you know the name of the files
 
make an array with the file names

---------------------------------------------------------

$fileContents = array();
$files = array(
'filename' => 'file1.txt',
'filename2' => 'file2.txt',
'filename3' => 'etc.txt');
$numFiles = count($files);
for($i = 0; $i < $numFiles; $i++)
{
$tempOpen = fopen($file, 'r');
$fileContents[$i] = fread($tempOpen, 500);
fclose($tempOpen);
echo $fileContents[$i];
}

-----------------------------------------

That should work.
The file names are just for convince. no big deal

So, you could do
echo $fileContents['filename'];
or
echo $fileContents[0];
 
make an array with the file names

---------------------------------------------------------

$fileContents = array();
$files = array(
'filename' => 'file1.txt',
'filename2' => 'file2.txt',
'filename3' => 'etc.txt');
$numFiles = count($files);
for($i = 0; $i < $numFiles; $i++)
{
$tempOpen = fopen($file, 'r');
$fileContents[$i] = fread($tempOpen, 500);
fclose($tempOpen);
echo $fileContents[$i];
}

-----------------------------------------

That should work.
The file names are just for convince. no big deal

So, you could do
echo $fileContents['filename'];
or
echo $fileContents[0];
 
Back
Top