search
HomeBackend DevelopmentPHP TutorialTraverse the generated directory tree

1. Preface

When I was writing my last blog, I needed to use a directory tree structure to display my file structure, so I had to manually "traverse" all the folders and files. Later, I thought that this was too error-prone and very labor-intensive, so I thought about writing a php script to traverse the files and folders under a directory and generate a directory tree so that I can use the directory tree structure if needed in the future. Where, just run it directly. The directory tree structure currently generated by the script can be viewed directly through the browser, or downloaded to generate a txt file.

2. Introduction to ideas

 The idea of ​​generating a directory tree is very simple. Traverse the contents under the current folder and skip directly when encountering "." and "..". When encountering a folder, call it recursively. When encountering a file, save it to an array first, etc. After traversing the current folder, concatenate the files in the array. This operation is to generate the directory tree. After generation, there is another step to display or download the directory tree. There are still some details in the writing process, which will not be revealed until development. In order to make it easy to understand and expand, I put what can be done by a function into a class to make the idea of ​​traversing the folder clearer.

3. Code implementation

  Now that I have the idea, I feel comfortable writing code (this is also why good people often tell us that they even spend more time thinking about it when writing code, instead of writing code immediately). Let’s take a look at some of the code:

 3.1 Generate directory tree

<span> 1</span>     <span>/*</span><span>*
</span><span> 2</span> <span>     * 生成目录树
</span><span> 3</span>      <span>*/</span>
<span> 4</span>     <span>public</span> <span>function</span> createTree(<span>$path</span>, <span>$level</span>=0<span>){
</span><span> 5</span>         <span>$level</span>       = <span>$level</span><span>;
</span><span> 6</span>         <span>$this</span>->tree .= <span>str_repeat</span>(<span>$this</span>->options["padding"], <span>$level</span><span>)
</span><span> 7</span>                         .<span>$this</span>->options["dirpre"<span>]
</span><span> 8</span>                        .<span>$this</span>->_basename(<span>$path</span><span>)
</span><span> 9</span>                        .<span>$this</span>->options["newline"<span>];
</span><span>10</span>         <span>$level</span>++<span>;
</span><span>11</span>         <span>$dirHandle</span>  = <span>opendir</span>(<span>$path</span><span>);
</span><span>12</span>         <span>$files</span>      = <span>array</span><span>();
</span><span>13</span>         <span>while</span> (<span>false</span> !== (<span>$dir</span> = <span>readdir</span>(<span>$dirHandle</span><span>))) {
</span><span>14</span>             <span>if</span>(<span>$dir</span> == "." || <span>$dir</span> == ".."<span>){
</span><span>15</span>                 <span>continue</span><span>;
</span><span>16</span> <span>            }
</span><span>17</span>             <span>if</span>(!<span>$this</span>->options["showHide"] && <span>substr</span>(<span>$dir</span>, 0, 1) == "."<span>){
</span><span>18</span>                 <span>continue</span><span>;
</span><span>19</span> <span>            }
</span><span>20</span>             <span>$dir</span>     = <span>$path</span>.DIRECTORY_SEPARATOR.<span>$dir</span><span>;
</span><span>21</span>             <span>if</span>(<span>is_dir</span>(<span>$dir</span><span>)){
</span><span>22</span>                <span>$this</span>->createTree(<span>$dir</span>, <span>$level</span><span>);
</span><span>23</span>             } <span>elseif</span> (<span>is_file</span>(<span>$dir</span><span>)){
</span><span>24</span>                 <span>array_push</span>(<span>$files</span>, <span>$dir</span><span>);
</span><span>25</span> <span>            }
</span><span>26</span> <span>        }
</span><span>27</span>         <span>closedir</span>(<span>$dirHandle</span><span>);
</span><span>28</span>         <span>foreach</span> (<span>$files</span> <span>as</span> <span>$key</span> => <span>$value</span><span>) {
</span><span>29</span>             <span>$this</span>->tree .= <span>str_repeat</span>(<span>$this</span>->options["padding"], <span>$level</span><span>)
</span><span>30</span>                             .<span>$this</span>->options["filepre"<span>]
</span><span>31</span>                             .<span>$this</span>->_basename(<span>$value</span><span>)
</span><span>32</span>                               .<span>$this</span>->options["newline"<span>];
</span><span>33</span> <span>        }
</span><span>34</span>         <span>return</span> <span>$this</span><span>;
</span><span>35</span>     }
View Code

 3.2 Display directory tree

<span>1</span>     <span>/*</span><span>*
</span><span>2</span> <span>     * 显示目录树
</span><span>3</span>      <span>*/</span>
<span>4</span>     <span>public</span> <span>function</span><span> showTree(){
</span><span>5</span>         <span>echo</span> "<pre class="brush:php;toolbar:false">"
<span>6</span>              .<span>$this</span>-><span>tree
</span><span>7</span>              ."
"; 8 } View Code

 3.3 Download directory tree

<span>1</span>     <span>/*</span><span>*
</span><span>2</span> <span>     * 下载目录树文件
</span><span>3</span>      <span>*/</span>
<span>4</span>     <span>public</span> <span>function</span> downloadTree(<span>$name</span><span>){
</span><span>5</span>         <span>header</span>("Content-type:text/plain"<span>);
</span><span>6</span>         <span>header</span>("Content-Disposition:attachment;filename={<span>$name</span>}.txt"<span>);
</span><span>7</span>         <span>echo</span> <span>$this</span>-><span>tree;
</span><span>8</span>     }
View Code

 3.4 Under test

Use the following codes at both ends to test respectively:

<span>1</span> <span>$t</span> = <span>new</span> Dirtree(<span>array</span>("padding"=>"    ","newline"=>"<br>"<span>));
</span><span>2</span> <span>$t</span>->createTree("D:\autoload")->showTree("tree");
View Code

The above code will output the directory structure information to the browser, just like Figure 1:

                                                                                                   结 Figure 1 Output directory structure to browser Figure 2 download directory tree structure

<span>1</span> <span>$t</span> = <span>new</span> Dirtree(<span>array</span>("padding"=>"    ","newline"=>"\r\n"<span>));
</span><span>2</span> <span>$t</span>->createTree("D:\autoload")->downloadTree("tree");
View Code

After the above code is executed, the browser will download a tree.txt file, and the information about opening the file is shown in Figure 2 4. Summary

 The function of generating a directory tree is basically completed, but if you have time, you can expand it to make it more friendly and support the command line mode. Or enhance the output content so that the folder can be folded (js implementation).

 The copyright of this article belongs to the author iforever (luluyrt@163.com). Any form of reprinting is prohibited without the author's consent. After reprinting the article, the author and the original text link must be provided in an obvious position on the article page, otherwise the right to pursue legal liability is reserved. .

The above introduces the traversal to generate a directory tree, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools