我的代码:
$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行/文件),但是每次我把一行变成新文件时,任何人都能帮我找出我做错的地方吗?
发布于 2015-07-08 03:28:36
您正在为每一行打开一个新文件,它覆盖最后一行,这就是为什么每个文件只有一行。这可能不是你想要的方式。
相反,循环遍历并得到200行的组,然后编写。这意味着一个1001行文件将有6写,而不是1001。这种方式将使比其他方法快得多。
$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的建议要好得多
发布于 2015-07-08 03:24:21
如下所示。您的文件写入应该放在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++;
}发布于 2015-07-08 03:31:22
你离我很近。只有对代码进行细微的更改才能使代码正常运行。
$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);
}
?>https://stackoverflow.com/questions/31282729
复制相似问题