尝试更新文本文件中的文本时,不会创建新行

时间:2013-07-27 21:35:54

标签: php

我尝试使用以下代码更新文本文件:

$filename = "flat-file-data.txt"; // File which holds all data
$rowToUpdate = $_REQUEST['number']; // This is line need to be updated
$newString = $_REQUEST['line'].'\r\n'; // This is what you want to replace it with

$arrFp = file( $filename ); // Open the data file as an array
// Replace the current element in array which needs to be updated with new string
$arrFp[$rowToUpdate-1] = $newString; 
$numLines = count( $arrFp ); // Count the elements in the array

$fp = fopen( $filename, "w" ); // Open the file for writing
for($i=0; $i < $numLines; $i++)
{
    fwrite($fp, $arrFp[$i]);
}
fclose( $fp ); // Close the file

从上面的代码可以看出,它将使用$ newString中的数据更新第1行,它应该能够在每行之后使用'\ r \ n'创建一个新行。

不幸的是,它不会创建一个新行,它只是在同一行或在当前行中,例如'这是第一行\ r \ n这是第二行'。是否有任何准确的方法可以在像

这样的新行中创建它
this is the firstline
this is the secondline

依旧等等?

1 个答案:

答案 0 :(得分:1)

您必须将\r\n放在双引号中:

$newString = $_REQUEST['line']."\r\n";
相关问题