How do I put into an array the items in a directory?
I have a directory th开发者_JAVA技巧at contains about 2000 text documents and I want to iterate through each one to parse the data. How can I do this?
scandir()
will bring all filenames into an array.
array scandir ( string $directory [, int $sorting_order = 0 [, resource $context ]] )
<?php
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);
?>
Why don't you check the PHP manual on the DirectoryIterator page? Nice class
http://php.net/manual/en/class.directoryiterator.php
The rest are trivial..
I assume you are interested in doing this in php. The key functions you will wind up using are the scandir function and the file_get_contents function.
So, you're source will look something like this:
<?php
$my_dir_path = "/path/to/my/dir";
$files = scandir($my_dir_path);
$files_contents_to_array = new Array(); // will contain a mapping of file name => file contents
if($files && count($files) > 0) {
for($files as $file) {
if($file /* some pattern check, verify it is indeed the file you need */) {
$files_contents_to_array[$file] = file_get_contents($file);
}
}
}
?>
I think this might be what you are looking for.
精彩评论