将目录中的所有文件合并到一个文本文件中

时间:2013-06-06 21:19:27

标签: php file

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

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

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

然后我会把那个数组写成一个新的文本文件,我已经不再在目录中找到文件了。

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

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

4 个答案:

答案 0 :(得分:9)

OrangePill的回答是错误的。

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

这是正确的答案:

  //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;

享受!

答案 1 :(得分:2)

你这样做的方式是消耗大量内存,因为它必须保存内存中所有文件的内容......这种方法可能会更好一点

首先获取您想要的所有文件

  $files = glob("/path/*.*");

然后打开输出文件句柄

  $out = fopen("newfile.txt", "w");

然后循环读取和写入文件。

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

然后清理

  fclose($out);

答案 2 :(得分:2)

试试这个:

<?php
//Name of the directory containing all files to merge
$Dir = "directory";


//Name of the output file
$OutputFile = "filename.txt";


//Scan the files in the directory into an array
$Files = scandir ($Dir);


//Create a stream to the output file
$Open = fopen ($OutputFile, "w"); //Use "w" to start a new output file from zero. If you want to increment an existing file, use "a".


//Loop through the files, read their content into a string variable and write it to the file stream. Then, clean the variable.
foreach ($Files as $k => $v) {
    if ($v != "." AND $v != "..") {
        $Data = file_get_contents ($Dir."/".$v);
        fwrite ($Open, $Data);
    }
    unset ($Data);
}


//Close the file stream
fclose ($Open);
?>

答案 3 :(得分:0)

尝试以下代码并享受!!!

/* Directory Name of the files */
$dir = "directory/subDir";
/* Scan the files in the directory */
$files = scandir ($dir);
/* Loop through the files, read content of the files and put then OutFilename.txt */
$outputFile = "OutFilename.txt";
foreach ($files as $file) {
    if ($file !== "." OR $file != "..") {
        file_put_contents ($outputFile, file_get_contents ($dir."/".$file),  FILE_APPEND);
    }
}
相关问题