dongranding3909 2017-01-09 17:57
浏览 95
已采纳

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

I have multiple .m3u files containing strings like:

string1
string2 etc //(with the line break)

I want to add this information into one file but when it gets to the end of a file, add a line break. Because when i do the code it works but when it connects the next file i get results like:

string10
string11string12
string13

I want to prevent this and add everything to new line. Code below:

<?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."
"); //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);
?>

I use:

fwrite($out, $line."
");

but then i get results like:

string1

string2
string3

string4

string5
  • 写回答

2条回答 默认 最新

  • douseda0009 2017-01-09 18:01
    关注

    Before adding your own linebreak - remove all linebreaks that can be in a string with trim (or even empty lines):

    foreach($filepathsArray as $file){
      $in = fopen($file, "r");
      while ($line = fgets($in)) {
           $line = trim($line);
           if ($line) {
               // if line is not empty - write it to a file
               fwrite($out, $line . "
    ");
           }
      }
      fclose($in);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题