dongqing4070 2013-02-19 18:24
浏览 19
已采纳

读取目录中的所有文件并处理文件字符串的最佳实践

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.

  • 写回答

1条回答 默认 最新

  • donglin4636 2013-02-19 18:26
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题