doufunuo4787 2013-09-25 16:41
浏览 53
已采纳

PHP列出目录中的所有文件 - 链接到文件?

Related to this post: "PHP list all files in directory" , specifically the code displayed by "Apr 19 '12 at 12:24 " Kiko"

I was wondering if anyone can suggest how to determine the folder path to the file itself: i.e.

$html .= "<li><span class='file'><a href='???' target='_blank'>". $eachDirectory ."</a></span></li>";

S I can wrap an HREF around it so it. The functions are recursive so I'm not sure at which stage I can determine the path of the file. Anyone have a way to do this? Thanks!

  • 写回答

1条回答 默认 最新

  • dsio68964998 2013-09-25 17:33
    关注

    I've looked at the referenced code and I have modified it to suite your needs. Replace ONLY the createTree function with this and try it

    function createTree($directory,$parent = '')
    {
        $html = "<ul>";
    
        foreach($directory as $keyDirectory => $eachDirectory)
        {
            if(is_array($eachDirectory))
            {
                $html .= "<li class='closed'><span class='folder'>" . $keyDirectory . "</span>";
                $html .= createTree($eachDirectory,$keyDirectory);
                $html .=  "</li>";
            }
            else
            {
                $origin = 'imgs';
                if(trim($parent) !== ''){
                    $path = $origin . '/' . $parent . "/" .$eachDirectory;
                }else{
                    $path = $origin . '/' . $eachDirectory;
                }
                $html .= "<li><span class='file'><a href='" . $path . "' target='_blank'>". $eachDirectory ."</a></span></li>";
    
            }
        }
        $html .= "</ul>";
    
        return $html;
    }
    

    You will notice that I've added a new argument item to the argument list of that function called $parent. This is used to carry the folder name of the parent folder of the item that will be linked. The folder name is then appended to the $origin variable (which is the name of the folder you traversed using the getFolderTree function , in my case it's 'imgs'.

    There is an if-else statement that checks if the $parent is empty, it's pretty self explanatory from there. If you want clarification please ask.

    NOTE 1: You need to replace the $origin value to the name of the folder at the root to get full paths

    NOTE 2: You need to replace the forwardslash (/) to that of your system e.g. for *NIX it's a backslash so for PHP you need to use a double-backslash when working inside of strings but if you're on Windows my edit will work fine

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)