Traverse 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> }
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 }
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> }
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");
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");


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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety
