首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用PHP将每200行写入新文件

用PHP将每200行写入新文件
EN

Stack Overflow用户
提问于 2015-07-08 02:52:56
回答 3查看 160关注 0票数 2

我的代码:

代码语言:javascript
复制
$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行/文件),但是每次我把一行变成新文件时,任何人都能帮我找出我做错的地方吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-07-08 03:28:36

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

相反,循环遍历并得到200行的组,然后编写。这意味着一个1001行文件将有6写,而不是1001。这种方式将使比其他方法快得多

代码语言:javascript
复制
$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的建议要好得多

票数 2
EN

Stack Overflow用户

发布于 2015-07-08 03:24:21

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

代码语言:javascript
复制
$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++;

}
票数 0
EN

Stack Overflow用户

发布于 2015-07-08 03:31:22

你离我很近。只有对代码进行细微的更改才能使代码正常运行。

  • $count = 0;改为$count = 1;
  • $file_path = "write_" . $counter++ . ".txt";行中,".txt"代替了"txt"
  • $count == 0改为$count = 0
  • 为了便于测试,我在4行之后拆分了文件。

代码:

代码语言:javascript
复制
<?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);
}
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31282729

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档