Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php文件函数修剪文本文件中的每一行_Php_Fopen - Fatal编程技术网

使用php文件函数修剪文本文件中的每一行

使用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

我有一个文本文件,有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个字符。新行字符不工作。有什么线索吗?

给每个操作系统换行

  • “\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