Take the 2-minute tour ×

I have 50 txt files, of which are basically replicates of an email, each txt file has the following format:

To: blabla@examplecom 
Subject: blabla 
From: bla1@example.com 
Message: This is a test message

The aim is to write a PHP script, which crawls through each file (all located within the same directory), and prints out a list of each 'unique' email address in the from field. The concept is very easy.

Can anyone point me in the right direction here? So far, I have managed to get my PHP script to read the contents of all of the files within the directory and output the result:

$directory = "emails/";
$dir = opendir($directory);
  $filename = $directory . $file;
  $type = filetype($filename);
  if ($type == 'file') {
     $contents = file_get_contents($filename);
     $items = explode('/n', $contents);
     echo '<table width="500" border="1" cellpadding="4">';
     foreach ($items as $item) {
       echo "<tr><td>$item</td></tr>\n";
     echo '</table>';

So now, I need to be able to retrieve the value assigned next to the 'From: ' string from each file, then displaying the output of that value, in a list.

Can anyone push me in the right direction here? Any code explanations would be beneficial, as I understand the concept and what I need to do, but syntactically I am struggling!

share|improve this question
Apologies, it is based on the question but with a different solution needed, I have re-edited the question, with the changes for the new requirement. –  Steve Aug 24 '11 at 17:07
add comment

1 Answer

$to = stristr($item, 'To: ');
$from = stristr($item, 'From: ');
$subject = stristr($item, 'Subject: ');
$message = stristr($item, 'Message: ');

if($to !== FALSE) echo $to;
elseif($from !== FALSE) echo $from;
elseif($subject !== FALSE) echo $subject;
elseif($message !== FALSE) echo $message;

This will get the values you are looking for. Just put this inside the foreach loop.

share|improve this answer
add comment

Your Answer


