将目录中的所有文件合并到一个文本文件 [英] merge all files in directory to one text file

查看:172
本文介绍了将目录中的所有文件合并到一个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,如何打开目录中的每个文件,所有文本文件并将它们全部合并为一个文本文件.

In PHP, how can I open everyfile, all text files, in a directory and merge them all into one text file.

我不知道如何打开目录中的所有文件,但是我会使用file()命令打开下一个文件,然后使用foreach将每一行附加到数组中. 像这样:

I don't know how to open all files in a directory, but I would use the file() command to open the next file and then a foreach to append each line to an array. like so:

$contents = array();
$line = file(/*next file in dir*/);
foreach($lines as line){
   array_push($line, $contents);
}

然后,我将该数组写入一个新的文本文件中,但目录中没有其他文件.

Then I would write that array to a new text file one I've reached no more files in the directory.

如果您有更好的方法,请告诉我.

if you have a better way of doing this then please let me know.

或者如果您可以帮助我实施我的解决方案,尤其是在dir中打开下一个文件,请告诉我!

Or if you can help me implement my solution especially the opening the next file in the dir, please let me know!

推荐答案

OrangePill的回答是错误的.

OrangePill's answer is WRONG.

它返回一个空文件和一个编译错误. 问题在于他使用fread(读取字节)而不是fget(读取行)

It returns an empty file and a compile ERROR. The problem was that he used fread (reads bytes) instead of fget (reads lines)

这是有效的答案:

  //File path of final result
    $filepath = "mergedfiles.txt";

    $out = fopen($filepath, "w");
    //Then cycle through the files reading and writing.

      foreach($filepathsArray as $file){
          $in = fopen($file, "r");
          while ($line = fgets($in)){
                print $file;
               fwrite($out, $line);
          }
          fclose($in);
      }

    //Then clean up
    fclose($out);

    return $filepath;

享受!

这篇关于将目录中的所有文件合并到一个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆