Home > Article > Backend Development > Traverse the generated directory tree and generate the directory tree_PHP tutorial
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.
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, it will be called recursively. When encountering a file, it will be saved into an array first. , after traversing the current folder, splice the files in the array together. 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.
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 the part Code:
" <span>6</span> .<span>$this</span>-><span>tree </span><span>7</span> .""; 8 } View Code
Use the following two ends of the code to test respectively:
1 $t = new Dirtree(array("padding"=>" ","newline "=>"The above code will output the directory structure information to the browser, just like Figure 1:
1 $t = new Dirtree(array("padding"=>" ","newline "=>"rn")); 2 $t->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
A directory tree generation function 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 consent of the author. After reprinting the article, the author and the original text link must be given in an obvious position on the article page, otherwise we will reserve the right to pursue it. Legal liability rights.