在PHP中将每200行写入新文件

时间:2015-07-08 02:52:57

标签: php fwrite

我的代码:

$file = "read_file.txt";
$file_path =  "write.txt";
$count = 0;
$counter = 1;

$lines = file($file);
foreach ($lines as $line) {
if($count == 200){
   $file_path =  "write_".$counter++."txt";
   $count == 0;
}
   $count++;
   $file_handle = fopen($file_path, "w");
   $file_contents = $line;
   fwrite($file_handle, $file_contents);
   fclose($file_handle);
}

我想将从文件中读取的每个新的200行写入新文件(换句话说将整个文件划分为200行/文件)但每次我将一行写入新文件时,任何人都可以帮我解决我做错的地方

4 个答案:

答案 0 :(得分:2)

您正在为每一行打开一个新文件,它会覆盖最后一行,这就是为什么每个文件只能获得一行的原因。这可能不是您想要的方式。

相反,循环并获取200行的组,然后写入。这意味着1001行文件将有6次写入,而不是1001.这种方式比其他方法 MUCH 更快

$count = 0;
$counter = 1;
$file_lines = '';

$lines = file("read_file.txt");
foreach ($lines as $line) {
   $file_lines .= $line . "\n";
   $count++;
   if($count == 200) {
      $file_handle = fopen("write_".$counter++."txt", "w+");
      fwrite($file_handle, $file_lines);
      fclose($file_handle);       
      $count = 0;
      $file_lines = '';
   }
}

编辑:Darren对array_chunk的建议对于可变长度数组会更好

答案 1 :(得分:1)

你的循环很糟糕,为什么不把你的$lines数组分成200个组(,如你所需),然后将它们写入单独的文件....

$lines = file($file);
$groups = array_chunk($lines, 200);
$counter = 0;
foreach ($groups as $group) {
    $file_path = "write_".$counter++.".txt";
    $file_handle = fopen($file_path, "w");
    fwrite($file_handle, implode("\n", $group));
}

参考:array_chunk()

Here's an example of how it chunks

答案 2 :(得分:0)

如下所示。你的文件写入应该是if条件。

get_card()

答案 3 :(得分:0)

你非常接近。只需要对代码运行良好进行微妙的更改。

  • $count = 0;已更改为$count = 1;
  • 使用$file_path = "write_" . $counter++ . ".txt";".txt"代替"txt"
  • $count == 0已更改为$count = 0
  • 我在4行之后拆分文件以便于测试

代码:

<?php
$file = "read_file.txt";
$file_path =  "write.txt";
$count = 1;
$counter = 1;

$lines = file($file);
foreach ($lines as $line) {
    echo "file path is $file_path\n";
    if($count == 4){
        print "reaching here\n";
        $file_path =  "write_". $counter++ . ".txt";
        $count = 0;
    }
   $count++;
   $file_handle = fopen($file_path, "w");
   $file_contents = $line;
   fwrite($file_handle, $file_contents);
   fclose($file_handle);
}
?>