我正在尝试在每行的末尾添加一个字符串。到目前为止这个工作。但是我不希望将字符串添加到第一行的末尾。我怎么能这样做?
到目前为止,我已经:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
while(!feof($baseFile)) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
我还尝试通过这样做来循环它:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
$x = 0;
while(!feof($baseFile)) {
if ($x > 0) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
$x++;
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
所以最终结果如下:
firstonestring secondonestring thirdonestring
等等。
我希望你能帮助我!
Ben:)
答案 0 :(得分:1)
只需在循环中添加一个计数器:
$counter = 0;
while(!feof($baseFile)) {
$line = fgets($baseFile)
if($counter++ > 0){
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}else{
$newFile.= $line . "\n";
}
}
此外,您似乎正在编写新文件,只是重新打开它并附加更多数据。没有必要这样做,只需在第一次写入内容之前附加内容:
fclose($baseFile);
file_put_contents("newfile.txt", $newFile . $EOLString);
//$bingName = "newfile.txt";
//$bingFile = fopen($bingName, "a+");
//fwrite($bingFile,$EOLString);
//fclose($bingFile);
另外,你可以只读入整个文件,分成几行,然后重新加入:
$EOLString="string \n";
$lines = explode("\n", file_get_contents("file.txt"));
$first = array_shift($lines);
file_put_contents("newfile.txt", $first . "\n" . implode($EOLString, $lines) . $EOLString);
//done!
答案 1 :(得分:0)
使用标志
$first = TRUE;//set true first time
while (!feof($baseFile)) {
$line = fgets($baseFile);
if (!$first) {// only enter for false
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}
$first = FALSE;// set false except first
}