开发者

Read file structure into an array, but only specific files

I have a directory structure that looks like this:

/expandables 
- folder
- folder
- folder
- folder 
  - BannerInfo.txt
  - index.html

Each one of the folder has the same exact stucture. One file named BannerInfo.txt and index.html. There are about 250 of these folders if that matters.

I want to loop through these folders and store each of the index.html files into an array. Inside of the index.html file is just some simple HTML and Javascript of which I want to read into a string to be displayed later on.

I'm struggling with how to filter out only the index.html file from the individual folders.

The purpose of this is because I want to randomly select an index.html file and put the contents into a textarea. I thought I could do a simple array_rand() on the returned array and spit out the string.

Any ideas?

EDIT:

I came up with something like this:

<?

    $expandables = array();

    $expandables = scandir("expandables/");

    $count = 0;

    foreach($expandables as $expandable) {
        if ($expandable != "." && $expandable != "..") {
            $expan开发者_Go百科dableCode = "expandables/" . $expandable . "/index.html";

            // get value of index.html for select list
            $expandableValue = file_get_contents($expandableCode);


            // echo out options
            echo "<option value='$expandableValue'>$expandable</option>";

        }
    }       



?>

But this isn't exactly working correctly. Is there a way to dynamically fill in my textarea with the index.html contents once I select it from the selectbox?


You can use readdir() or scandir() to get the contents of each directory (the filenames, that is). Use is_dir() to check if the found item is a file or a directory. If it is a directory, repeat the process on that directory. If it is a file, check if it's 'index.html' and if so, put in in the array.

It might be better to store the filenames (including paths) in the array instead of the content. Doing the latter will cause all of the 250 files to be read on each request.

Traversing the directory might be problematic enough, so it's better to cache this list too.

You can save the array of paths to a file. Then, you can load this file in an array, which is faster than checking all these directories. If the file does not exist, you can run the procedure to create it. If it does exist, you can check if it is older than, say, one day (or whatever suits you best). If any of the index.html files does not exist, you can also run the process of createing the file, because it apparently is not up to date anymore.

If you save this array as PHP code, you can include it. This will give you an even better performance if you got a PHP cache like APC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜