0

I have created a directory with the following files located within:

  • index.php
  • one.txt - Hello
  • two.txt - Ok
  • three.txt - Goodbye
  • four.txt - Cool

Everything in bold tells you what those text files contain.

What I am trying to do is echo out all of the contents of the text files into the index.php page. So when the user visits the index.php page, this is what they'll see:

Date: 13 May 2015
Contents of text file: Hello

Date: 12 May 2015
Contents of text file: Ok

Date: 11 May 2015
Contents of text file: Goodbye

Date: 10 May 2015
Contents of text file: Cool

As you can see from above, the date the text files were created along with its contents are all echoed out. Also, they are echoed out based on the order that they were last modified.

This is the code that I am trying to use to achieve this:

    <?php
    foreach (glob("*.txt") as $filename) {
      echo "Date:"; 
      echo date('d F Y', filemtime($filename)) . 
      "Contents of text file:";
      echo file_get_contents($filename);
     }
    ?>

What's happening in this code is that:

  • All of the text files in the directory are picked up
  • For each text file, it gets its last modification date and what it contains echoed out

The outcome of this code is that it is similar to what can be seen in the yellow box above (which is what I am trying to achieve) however the order of the echo is not in date order. It gets echoed out a little something like this:

  • 13 May
  • 10 May
  • 11 May
  • 12 May

How would I make it so that it gets echoed out based on the date that it was last modified? With the latest date at the top and the oldest date at the bottom?

  • Collect messages to array, sort it and then echo. – u_mulder May 22 '15 at 16:44
  • `Glob` doesn't guarantee an order to the entries returned. You need to sort them as you want them. Maybe useful: [glob() - sort by date](http://stackoverflow.com/questions/124958/glob-sort-by-date). Then use these entries to get and display the file contents. – Ryan Vincent May 22 '15 at 17:00

2 Answers2

0

Do this:

<?php
foreach (glob("*.txt") as $filename) {
  $result[date('Ymd', filemtime($filename))]= 
    "Date:". 
    date('d F Y', filemtime($filename)) . 
    "Contents of text file:".
    file_get_contents($filename);
 }
ksort($result);
echo implode("", $result);
?>
-1
<?php

foreach (glob("*.txt") as $filename) 
{
    $time = filemtime($filename);
    $files[$filename] = $time;
}

arsort($files);

foreach ($files as $file => $time) 
{
    "Contents of text file:";
    echo file_get_contents($file);
}

?>

Edit:

Thanks Glavić for the hint. I updated the script, so files don't get lost.

Scoutman
  • 1,630
  • 12
  • 20
  • If more files have identical modification time, there will be an collition, last file will only be available. – Glavić May 23 '15 at 11:03