我有问题。我想输出所有扩展名为.mp4的文件名。以下代码可以实现,但它只从一个目录输出。
<?php
if ($handle = opendir('/media/AB12-34/DCIM/100DCIM')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'mp4')
{
$thelist .= '<p><td><option value="'.$file.'">'.$file. '</option></td>';
}
}
closedir($handle);
我希望脚本输出/media/AB*/DCIM/100DCIM
(请注意星号)目录中所有目录中的所有.mp4文件。有没有办法使用opendir
命令执行此操作?尝试*但它没有工作。
答案 0 :(得分:0)
使用PHP5内置RecursiveDirectoryIterator之类的内容:
<?php
/**
* RecursiveDirectoryIterator function to get media.
*
* @param string $base_dir
* @param array $extentions
* @return array
*/
function get_media($base_dir, $extentions = array('mp4')) {
if(!file_exists($base_dir)) return array();
$extensions = implode('|', $extentions);
$directory = new RecursiveDirectoryIterator($base_dir);
$iterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($iterator, "/^.+\.$extensions$/i", RecursiveRegexIterator::GET_MATCH);
$ret = array();
foreach ($regex as $filename=>$object) {
$ret[] = $filename;
}
return $ret;
}
//print_r( get_media('/media/', array('mp4')) );
$thelist = '<select size="1" name="?">';
foreach (get_media('/media/', array('mp4')) as $file)
{
$thelist .= '<option value="'.$file.'">'.$file.'</option>';
}
$thelist .= '</select>';
echo $thelist;
?>
编辑(添加时间,见评论):
由于你基本上拥有文件的完整路径,你可以在迭代器函数中添加filectime($filename);
或在执行显示循环时将其添加到外部,下面是在函数内部进行。
<?php
/**
* RecursiveDirectoryIterator function to get media.
*
* @param string $base_dir
* @param array $extentions
* @return array
*/
function get_media($base_dir, $extentions = array('mp4')) {
if(!file_exists($base_dir)) return array();
$extensions = implode('|', $extentions);
$directory = new RecursiveDirectoryIterator($base_dir);
$iterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($iterator, "/^.+\.$extensions$/i", RecursiveRegexIterator::GET_MATCH);
$ret = array();
$i = 0;
foreach ($regex as $filename=>$object) {
$ret[$i]['filename'] = $filename;
$ret[$i]['filetime'] = filectime($filename);
$i++;
}
return $ret;
}
//print_r( get_media('/media/', array('mp4')) );
$thelist = '<select size="1" name="?">';
foreach (get_media('/media/', array('mp4')) as $file)
{
$thelist .= '<option value="'.$file['filename'].'">'.$file['filename'].' - '.date("F j, Y, g:i a",$file['filetime']).'</option>';
}
$thelist .= '</select>';
echo $thelist;
?>