0

I want to get all the file name from a directory, and sort by last modified date. I googled and get lots of answers, so I picked one from sort files by date in PHP

<?php
$files = array();
$dir = getcwd();
$dir = dirname($dir);  //get Parent directory
$dir .= "/XMLdata/*.xml";

$files = glob($dir);
usort($files, function($a, $b) {
    return filemtime($a) < filemtime($b);
});
    header('Content-type: application/json');
    echo json_encode($files);
?>

From the code above, I can get the all the xml file from the directory XMLdata, However, from the result $files. I get all the files, but with absolute Path, which is "c:\wamp\www/XMLdata/xxxx.xml", and I just want the file xxxx.xml. I could process it in javascript use regular expression, But I think there must be a better way to get just the file name. Can anyone help me, thanks.

If there is no good way, I can use

           str = result[numberIndex];//one of absolute path from php
           var array = str.split("/");
           str = array[array.length - 1];

I can get the right filename.

Idea from @born loser

<?php
$files = array();
$dir = getcwd();
$dir = dirname($dir);  //get Parent directory
$dir .= "/XMLdata/*.xml";

$files = glob($dir);
usort($files, function($a, $b) {
    return filemtime($b) < filemtime($a);
});
foreach($files as &$value)
{
     $value = substr($value,strrpos($value,'/')+1);
}
    header('Content-type: application/json');
    echo json_encode($files);
?>
Community
  • 1
  • 1
yongnan
  • 405
  • 7
  • 20

2 Answers2

1

why bother.. This is what i do:

$i = strrpos($_SERVER['PHP_SELF'],'/');
define('URLBASE',   substr($_SERVER['PHP_SELF'],0,$i+1));

If you can be sure to find a '/':

$sFile = substr($sPath,strrpos($sPath,'/')+1);
born loser
  • 420
  • 1
  • 4
  • 10
  • thanks, but I do not know how to add your lines of code. I can get the right file name, after processing each absolute path. – yongnan Jul 26 '14 at 16:37
  • thanks, I use foreach($files as &$value) { $value = substr($value,strrpos($value,'/')+1); }. – yongnan Jul 26 '14 at 20:34
  • Great :-) i didn't yet know the trick with the reference inside the foreach statement. thanks :-) – born loser Jul 26 '14 at 22:06
0

Sorry - yes the array $files would have the filenames in the directory ./

for ($i = 0; $i < sizeof($files); $i++) {
    echo $files[$i];
} 

would return all the filenames - you would just need to play around with the filemtime function in sorting them

(this is in reference to the first answer in the question you linked to)

Herb
  • 345
  • 1
  • 17
  • thanks, actually, I tried the first,but not get the result. and I think after ksort, we can get the array which is sort by date – yongnan Jul 26 '14 at 16:33