使用php文件函数修剪文本文件中的每一行
我有一个文本文件,有10行,每行50个字符。我想保留前10个字符,删除每行中的剩余字符。我使用了以下代码使用php文件函数修剪文本文件中的每一行,php,fopen,Php,Fopen,我有一个文本文件,有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.kn
<?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个字符。新行字符不工作。有什么线索吗?给每个操作系统换行
- “\r\n”:Windows的新行
- “\n”:UNIX/Linux/MacOS 10.8的新行+
- “\r”:旧MacOS的新行
<?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);
}
应该。也许您的编辑器更喜欢“\r\n”而不是“\n”作为新行。顺便说一句,您应该移动$new\u handle=fopen('test.knt',“a”)代码>不在循环中。只需使用EOL
而不是\r\n
作为操作系统即可insensitive@MarkusMalkusch你说得对,它正在工作。Thanks@Ohgodwhy请使用.EOL
指定语法,而不是\n