我有一个文本文件,每行有10行和50个字符。我想保留前10个字符并删除每行中的剩余字符。我使用了以下代码
<?php
$target_file = 'test.txt';
$handle = fopen($target_file, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$new_line=substr($line,0,10)."\n";
$new_handle=fopen('test.knt',"a");
fwrite($new_handle,$new_line);
}
}
fclose($new_handle);
?>
但输出文件包含100行的单行。新行字符不起作用。有线索吗?
答案 0 :(得分:0)
Newline每个操作系统
请参阅下面的代码/语法
<?php
$target_file = 'test.txt';
$new_target_file = 'test.knt';
$handle = fopen($target_file, "r");
$new_handle = fopen($new_target_file, "a"); // or use "w" instead "a" if you want to overwrite file everytime
if ($handle && $new_handle) {
while (($line = fgets($handle)) !== false) {
$new_line=substr($line,0,10) . "\r\n";
fwrite($new_handle,$new_line);
}
fclose($new_handle);
fclose($handle);
}