在PHP中,我如何打开每个文件,所有的文本文件,在一个目录中,并将它们合并成一个文本文件
我不知道如何打开目录中的所有文件,但我会使用file()
命令打开下一个文件,然后使用foreach将每一行附加到数组。像这样:
$contents = array();
$line = file(/*next file in dir*/);
foreach($lines as line){
array_push($line, $contents);
}
然后我将这个数组写入一个新的文本文件,如果我在目录中没有更多的文件。
如果你有更好的方法,请告诉我。
或者如果你能帮助我实现我的解决方案,特别是打开下一个文件在目录,请让我知道!
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;
享受吧!
你这样做的方式将消耗大量内存,因为它必须在内存中保存所有文件的内容…这种方法可能会好一点
首先获取所有你想要的文件
$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);
试试这个:
<?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);
?>
试试下面的代码吧!
/* 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);
}
}