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

Write each 200 lines to new file in PHP

我的代码:

$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 行/文件)但是每次我将一行写入新文件时,任何人都可以帮助我解决我的问题做错了

如下。您的文件写入应该放在 if 条件下。

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

$lines = file($file);
foreach ($lines as $line) {
   if($count == 0){ //Open a file and start writing.
    $file_path =  "write_".$counter++."txt";
    $file_handle = fopen($file_path, "w");
   }
   $file_contents = $line;
   fwrite($file_handle, $file_contents); //Append into the file

   if($count == 200){ //When it reach 200 close the file
    fclose($file_handle);
    $count = 0; //reset it to 0
   }
   $count++;

}

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

相反,循环并获取 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 = '';
   }
}

编辑:达伦对array_chunk的建议对于可变长度数组

会好得多

你们非常接近。只需对您的代码进行细微的更改即可正常运行。

  • $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);
}
?>

你的循环很糟糕,你为什么不把你的 $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