我的代码:
$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行/文件)但每次我将一行写入新文件时,任何人都可以帮我解决我做错的地方
答案 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));
}
答案 2 :(得分:0)
如下所示。你的文件写入应该是if条件。
get_card()
答案 3 :(得分:0)
你非常接近。只需要对代码运行良好进行微妙的更改。
$count = 0;
已更改为$count = 1;
$file_path = "write_" . $counter++ . ".txt";
行".txt"
代替"txt"
$count == 0
已更改为$count = 0
代码:
<?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);
}
?>