...

View Full Version : Sort and echo contents of multiple text files?



dbarak
04-28-2012, 02:41 AM
Hello everyone,

I'm trying to do something that I'm sure is very simple, but I'm having an unbelievably hard time doing it. I've even had some help from people online, but their suggestions haven't worked. I'm kind of new to PHP programming, but I'm starting to get the concept.

Anyway, I want to read a directory full of text files and display the contents - sorted by the file name they came from. Here's an example...

"Random phrase." in file-1.txt

"Alphabet." in file-2.txt

"Ship." in file-3.txt

I'd read in the three files and echo...

Random phrase.
Alphabet.
Ship.

They're sorted by file name, not by file contents. The code I've got so far displays the file names in order, but I can't get the contents to display. Overall, I know how to sort and echo things, and I know how to echo the contents of text files, but I can't figure out how to do both. What you'll see here is just test code so I can sort out (pun intended) the problem.



<?php

$dirFiles = array();
if ($handle = opendir('./event-titles'))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$dirFiles[] = $file;
}
}
closedir($handle);
}
sort($dirFiles);
foreach($dirFiles as $file)
{
$fileContents = file_get_contents($file);
echo $file."<br>".$fileContents."<br><br>";
}
?>


I'm kind of stupid, so please be gentle. :D I'm trying to learn as I go, and I usually comment out code until I break something, then I go and put it back in. I tend to dissect code in order to learn it - I ain't too pretty durn good at book larnin'.

Dave

Fou-Lu
04-28-2012, 05:30 AM
Read the contents into an array as well. I don't know whether these have multiple lines, nor if you need to keep track of the files they came from, so I'll just assume both.


$aContents = array();
foreach ($dirFiles AS $file)
{
if ($fp = fopen($file, 'r'))
{
while (false !== ($line = fgets($fp)))
{
$line = trim($line);
if (!isset($aContents[$line]))
{
$aContents[$line] = array();
}
$aContents[$line][] = $file;
}
fclose($fp);
}
}

ksort($aContents);

foreach ($aContents AS $phrase => $aFile)
{
printf('Phrase: %s found in files: %s', $phrase, implode(', ', $aFile));
}




BTW, if you don't care about file association, just file() all the files into an array_merge (if you need to deal with multiple lines), and sort that one.

dbarak
04-30-2012, 04:33 PM
Thanks Fou-Lu! This gives me a direction to follow. Much appreciated.

Dave



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum