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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools