Php 打开多个文件并将其数据写入一个文件,包括换行符

Php 打开多个文件并将其数据写入一个文件,包括换行符,php,Php,我有多个.m3u文件,其中包含以下字符串: string1 string2 etc //(with the line break) 我想将此信息添加到一个文件中,但当它到达文件末尾时,请添加一个换行符。因为当我编写代码时,它会工作,但当它连接下一个文件时,我会得到如下结果: string10 string11string12 string13 string1 string2 string3 string4 string5 我想阻止这一切,并添加到新的行。 代码如下: <?PHP

我有多个.m3u文件,其中包含以下字符串:

string1
string2 etc //(with the line break)
我想将此信息添加到一个文件中,但当它到达文件末尾时,请添加一个换行符。因为当我编写代码时,它会工作,但当它连接下一个文件时,我会得到如下结果:

string10
string11string12
string13
string1

string2
string3

string4

string5
我想阻止这一切,并添加到新的行。 代码如下:

<?PHP
//File path of final result
$longfilepath = "/var/lib/mpd/playlists/";

$filepathsArray = [$longfilepath."00's.m3u",$longfilepath."50's.m3u",$longfilepath."60's.m3u",$longfilepath."70's.m3u",$longfilepath."80's.m3u",$longfilepath."90's.m3u",$longfilepath."Alternative Rock.m3u",$longfilepath."Best Of Irish.m3u",$longfilepath."Blues.m3u",$longfilepath."Chart Hits.m3u",$longfilepath."Christmas.m3u",$longfilepath."Classic Rock.m3u",$longfilepath."Classical Opera.m3u",$longfilepath."Country.m3u",$longfilepath."Dance.m3u",$longfilepath."Disco.m3u",$longfilepath."Easy Listening.m3u",$longfilepath."Electric Rock.m3u",$longfilepath."Hard Rock.m3u",$longfilepath."Irish Country.m3u",$longfilepath."Jazz.m3u",$longfilepath."Live and Acoustic.m3u",$longfilepath."Love Songs.m3u",$longfilepath."Pop.m3u",$longfilepath."Rap and RnB.m3u",$longfilepath."Reggae.m3u",$longfilepath."Relaxation.m3u",$longfilepath."Rock and Roll.m3u",$longfilepath."Rock.m3u",$longfilepath."Soul.m3u",$longfilepath."Soundtracks.m3u",$longfilepath."Top Bands.m3u"];
$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)){
       fwrite($out, $line."\n"); //My attempt to add new line (which works) but then adds an extra for those that dont need it.
  }
  fclose($in);
}

//Then clean up
fclose($out);
?>
但我得到的结果如下:

string10
string11string12
string13
string1

string2
string3

string4

string5

在添加您自己的换行符之前-删除可以包含在带有
trim
的字符串中的所有换行符(甚至是空行):

这可能更容易:

$out = array();
foreach($filepathsArray as $file) {
    $out = array_merge($out, file($file, FILE_IGNORE_NEW_LINES, FILE_SKIP_EMPTY_LINES));
}
file_put_contents($filepath, implode("\n", $out));
  • 将文件读入数组,忽略换行符和空行
  • 使用换行符内爆数组并写入最终文件

注意:您可能需要在
\r\n
上内爆,才能在某些Windows应用程序(如记事本)中看到换行符。

您还可以跳过while循环中的空行,效果非常好!我仍然在文本文件的末尾留下了一行新行,如何删除空的新行?谢谢嗯,这里您需要检查这是否是最后一个文件中的最后一行,而不是添加
\n
。但是你真的需要它吗?我的系统抓取了文件中的每一条线,并将数据加载到一个li元素中,因此我会留下一个空白元素。如果它是一行代码,可以排序,那么这将是伟大的,但如果它超过了几行代码,那么我想我会围绕它进行构建!例如,您可以在输出行时检查行是否为空,而不是在合并行时检查行是否为空。