读取目录中的所有文件并处理文件字符串的最佳实践
In Java there is the File object that I can use to refer to a file's parent, list children files, and other useful functions (methods). These methods can return File objects, so I don't need to deal with a file's string. Instead, I can just manage the object. This makes things nice and neat and less prone to my typos.
In PHP I am concatenating the directory string with the file name string to get the file string. It works fine, but this seems gimmicky to me, and I would like to know if there is a better way. Is there a PHP equivalent to the built in Java File object?
Here is my code for reading all files in a directory and printing out their contents line by line:
$reportDir = realpath(RESOURCE_PATH . "/userFiles/uploadedReports");
if ($dirHandle = opendir($reportDir)) {
while (false !== ($entry = readdir($dirHandle))) {
if ($entry != "." && $entry != ".."){
$fileString = $reportDir . "/" . $entry;
$fileHandle = fopen($fileString, "r");
while (!feof($fileHandle) ) {
$line = fgets($fileHandle);
echo $line . "<br />";
}
fclose($fileHandle);
$i++;
}
}
closedir($dirHandle);
}
In case you want to know exactly what I am trying to accomplish with this code, I am going to display to the user an HTML table with data from a tab delimited file.
Yes there is its an SPL class called SplFileObject
which has methods for dealing with the file contents... There is also its parent SplFileInfo
which has methods for basic file information (mtime, path, filename, etc..). There are also a series of iterators for dealing with iterating over structures such as a directory/file tree.